矩陣乘法和龜速乘這樣寫!
阿新 • • 發佈:2021-10-13
明顯的矩陣乘法題。
模數很大,要用龜速乘。
寫法:
矩陣寫在結構體裡,不要用過載運算子,結構體內寫乘法函式。
下面有龜速乘的模板。
//標頭檔案省略 ll n,mod; #define madd(a,b) {a=((a+b)%mod+mod)%mod;} #define mmul(a,b) {a=(a*b%mod+mod)%mod;} inline ll cheng(ll a,ll b){//龜速乘 ll res=0; a%=mod; b%=mod; while(b){ if(b&1){ madd(res,a); } b>>=1; a=(a<<1)%mod; } return res; } struct matrix{ ll m[11][11]; matrix mul(matrix x){ matrix res; ll ans; For(i,0,10){ For(j,0,10){ ans=0; For(k,0,10){ madd(ans,cheng(m[i][k],x.m[k][j])); } res.m[i][j]=ans; } } return res; } }a,b,c; void pw(ll x){ For(i,0,10) b.m[i][i]=1; while(x>0){ if(x&1){ b=b.mul(a); } x>>=1; a=a.mul(a); } } signed main(){ IOS; ll p,q,r,t,u,v,w,x,y,z; cin>>n>>mod>>p>>q>>r>>t>>u>>v>>w>>x>>y>>z; ll t1[11][11]={ {p,1,1,0,1,0,0,0,0,0,0}, {q,0,0,0,0,0,0,0,0,0,0}, {1,0,u,1,1,0,0,0,0,0,0}, {0,0,v,0,0,0,0,0,0,0,0}, {1,0,1,0,x,1,0,0,0,0,0}, {0,0,0,0,y,0,0,0,0,0,0}, {r,0,0,0,0,0,1,0,0,0,0}, {t,0,0,0,1,0,2,1,0,0,0}, {0,0,1,0,0,0,0,0,w,0,0}, {0,0,0,0,1,0,0,0,0,z,0}, {1,0,0,0,2,0,1,1,0,0,1} }; For(i,0,10) For(j,0,10) a.m[i][j]=t1[i][j]; pw(n-2); ll t2[11][11]={ {3,1,3,1,3,1,1,1,w,z,1}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0} }; For(i,0,10) For(j,0,10) c.m[i][j]=t2[i][j]; c=c.mul(b); cout<<"nodgd "<<c.m[0][0]<<"\nCiocio "<<c.m[0][2]<<"\nNicole "<<c.m[0][4]<<"\n"; return 0; }
本文作者為小蒟蒻:zhangshaojia
轉載請註明原文連結。
碼字不易,求關照,謝謝!