其他分享
首页 > 其他分享> > #矩阵乘法# [luogu 3216] [HNOI2011]数学作业

#矩阵乘法# [luogu 3216] [HNOI2011]数学作业

作者:互联网

Porblem

https://www.luogu.com.cn/problem/P3216


Solution


Code

#include<cstdio> 
#include<cstring>
#include<algorithm>
#define ll long long
#define rep(i,x,y) for(ll i=x;i<=y;i++)
using namespace std; 
const int N=10; 
ll n,mod,W=3;  
struct Matrix{
	ll a[N][N]; 
	Matrix operator *(const Matrix &b) const{
		Matrix c; memset(c.a,0,sizeof(c.a)); 
		rep(i,1,W) rep(j,1,W) rep(k,1,W) c.a[i][j]=(c.a[i][j]+a[i][k]*b.a[k][j]%mod)%mod; 
		return c; 
	}
}f,ans;
ll ksm(ll x,ll y){
	ll cnt=1; 
	for(;y;y>>=1,x=(x*x)) if (y&1) cnt=(cnt*x); 
	return cnt; 
}
Matrix Q(Matrix x,ll y){
	Matrix tmp,ret; 
//	memset(tmp.a,0,sizeof(tmp.a)); 
	memcpy(tmp.a,x.a,sizeof(x.a)); 
	memset(ret.a,0,sizeof(ret.a)); 
	rep(i,1,W) ret.a[i][i]=1; 
	for(;y;y>>=1,tmp=tmp*tmp) if (y&1) ret=ret*tmp; 
	return ret; 
}
int main(){
	scanf("%lld%lld",&n,&mod); 
	ll tot=0,Fn=n; 
	while (Fn) Fn/=10,tot++; 
	memset(ans.a,0,sizeof(ans.a)); 
	ans.a[1][3]=1; 
	rep(i,1,tot){
		ll q=ksm(10,i-1); 
		memset(f.a,0,sizeof(f.a)); 
		f.a[1][1]=q%mod*10%mod; 
		f.a[2][2]=f.a[2][1]=f.a[3][1]=f.a[3][2]=f.a[3][3]=1; 
		if (i!=tot) ans=ans*Q(f,(q*9)); else ans=ans*Q(f,(n-q+1)); 
	}
	printf("%lld",ans.a[1][1]); 
	return 0; 
}

标签:tmp,3216,Matrix,luogu,ll,ret,HNOI2011,ans,sizeof
来源: https://blog.csdn.net/qq_39897867/article/details/114433407