BZOJ 4128 Matrix

    xiaoxiao2021-03-25  112

    Description

    给定矩阵A,B和模数p,求最小的x满足 A^x = B (mod p)

    Input

    第一行两个整数n和p,表示矩阵的阶和模数, 接下来一个n * n的矩阵A. 接下来一个n * n的矩阵B

    Output

    输出一个正整数,表示最小的可能的x,数据保证在p内有解

    Sample Input

    2 7 1 1 1 0 5 3 3 2

    Sample Output

    4

    HINT

    对于100%的数据,n <= 70,p <=19997,p为质数,0<= A_{ij},B_{ij}< p 保证A有逆

    Source

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    BSGS+矩阵乘法~

    显然是BSGS,然后重载一下运算符,把矩阵当做数来算就可以了。过程和普通的BSGS是一样的。

    注意:

    (1)每次乘是乘到m不是c!因为这个T到飞起啊- -

    (2)一定要重载<、>、==三种符号……否则会出现一堆奇奇怪怪的东西,并不明白是为什么。

    #include<cstdio> #include<cstring> #include<cmath> #include<map> using namespace std; int n,m,c,num; struct node{ int a[71][71]; bool operator < (const node &v) const { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(a[i][j]<v.a[i][j]) return 1; else if(a[i][j]>v.a[i][j]) return 0; return 0; } bool operator > (const node &v) const { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(a[i][j]<v.a[i][j]) return 0; else if(a[i][j]>v.a[i][j]) return 1; return 0; } bool operator == (const node &v) const { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(a[i][j]!=v.a[i][j]) return 0; return 1; } }a,b,ans,now; int read() { int totnum=0,f=1;char ch=getchar(); while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();} while(ch>='0' && ch<='9') {totnum=(totnum<<1)+(totnum<<3)+ch-'0';ch=getchar();} return totnum*f; } node operator *(node u,node v) { node z; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { z.a[i][j]=0; for(int k=1;k<=n;k++) z.a[i][j]=(z.a[i][j]+u.a[i][k]*v.a[k][j])%c; } return z; } node mi(node u,int v) { node z; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i==j) z.a[i][j]=1; else z.a[i][j]=0; while(v) { if(v&1) z=z*u; u=u*u;v>>=1; } return z; } int main() { n=read();c=read(); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a.a[i][j]=read(); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) b.a[i][j]=read(); m=sqrt(c); if(m*m!=c) m++; map<node,int> ma; ans=b;ma[ans]=0; for(int i=1;i<=m;i++) { ans=ans*a;ma[ans]=i; } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i==j) ans.a[i][j]=1; else ans.a[i][j]=0; now=mi(a,m); for(int i=1;i<=m;i++) { ans=ans*now; if(ma[ans]) { num=i*m-ma[ans]; printf("%d\n",((num%c)+c)%c); return 0; } } }

    转载请注明原文地址: https://ju.6miu.com/read-11903.html

    最新回复(0)