[HNOI2011]数学作业 分段矩阵乘法
给n,问123……n这个数字串模m的数值,n<=1e18
对于0-9,10-99,这些数字之间都满足f(n)=f(n-1)*10^c,c定值
这每一段都可以做矩阵快速幂 ,存一下[f(n),n,1]就行
#include<bits/stdc++.h> #include<stdio.h> #include<algorithm> #include<queue> #include<string.h> #include<iostream> #include<math.h> #include<set> #include<map> #include<vector> #include<iomanip> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define FOR(a) for(int i=1;i<=a;i++) const int inf=0x3f3f3f3f; const ll Linf=9e18; const int maxn=1e5+7; //const ll mod=100003; const double eps=1e-6; ll mod; struct mat{ ll a[4][4]; int n,m; mat(){memset(a,0,sizeof a);n=0;m=0;} mat(int x,int y){memset(a,0,sizeof a);n=x;m=y;} mat operator* (const mat &rhs)const{ mat ans; ans.n=n;ans.m=rhs.m; for(int i=1;i<=n;i++){ for(int j=1;j<=rhs.m;j++){ for(int k=1;k<=m;k++){ ans.a[i][j]=(ans.a[i][j]+a[i][k]*rhs.a[k][j])%mod; } } } return ans; } mat operator^ (ll rhs)const{ mat ans(n,n),b=*this; for(int i=1;i<=n;i++)ans.a[i][i]=1; for(;rhs;rhs>>=1,b=b*b) if(rhs&1)ans=ans*b; return ans; } }; int main(){ ll n,c; mat ans(1,3),b(3,3); scanf("%lld%lld",&n,&mod); ans.a[1][3]=1; for(int i=1;i<=3;i++){ for(int j=1;j<=i;j++){ b.a[i][j]=1; } } for(ll i=10;;i*=10){ b.a[1][1]=i%mod; if(i<=n)c=i/10*9; else c=n-i/10+1; ans=ans*(b^c); if(i>n)break; } printf("%lld\n",ans.a[1][1]); return 0; }