Description
小 C 数学成绩优异,于是老师给小 C 留了一道非常难的数学作业题:给定正整数 N 和 M 要求计算 Concatenate (1 ..
N) Mod M 的值,其中 Concatenate (1 ..N)是将所有正整数 1, 2, …, N 顺序连接起来得到的数。 例如,N
= 13, Concatenate (1 .. N)=12345678910111213.小C 想了大半天终于意识到这是一道不可能手算出来的题目, 于是他只好向你求助,希望你能编写一个程序帮他解决这个问题。
Input
只有一行且为用空格隔开的两个正整数N和M, 1≤N≤10^18且1≤M≤10^9.
Output
仅包含一个非负整数,表示 Concatenate (1 .. N) Mod M 的值。
Sample Input
13 13
Sample Output
4
题解
列个表
12=1*10+2
123=12*10+3 …..
12345678910=123456789*100+10
1234567891011=12345678910*100+11….
于是你可以发现,对于乘10,100,1000这些是有连续一段的
所以我们搞18个矩阵,然后跑矩乘
矩阵不满足交换律所以因此调了好久。。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
LL n,mod;
struct matrix
{
LL m[4][4];
matrix(){memset(m,0,sizeof(m));}
}pre[20],st;
matrix mul(matrix u,matrix v,int n,int m,int p)
{
matrix ret;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
for(int k=1;k<=p;k++)
ret.m[i][k]=(ret.m[i][k]+(u.m[i][j]*v.m[j][k]))%mod;
return ret;
}
matrix pow_mod(matrix u,LL b)
{
matrix ans;
for(int i=1;i<=3;i++)ans.m[i][i]=1LL;
while(b)
{
if(b%2==1)ans=mul(ans,u,3,3,3);
u=mul(u,u,3,3,3);b/=2;
}
return ans;
}
int main()
{
scanf("%lld%lld",&n,&mod);
LL tmp=n;int cnt=0;
while(tmp!=0){cnt++;tmp/=10;}
tmp=1LL;
for(int i=1;i<=cnt;i++)
{
tmp*=10;
pre[i].m[1][1]=tmp%mod;
pre[i].m[2][1]=pre[i].m[2][2]=pre[i].m[3][2]=pre[i].m[3][3]=1LL;
}
st.m[1][1]=0LL;st.m[1][2]=1LL;st.m[1][3]=1LL;
tmp=1LL;
matrix P;for(int i=1;i<=3;i++)P.m[i][i]=1LL;
for(int i=1;i<cnt;i++)
{
tmp*=10;
// for(int j=tmp/10;j<tmp;j++)P=mul(P,pre[i],3,3,3);
P=mul(P,pow_mod(pre[i],tmp-tmp/10),3,3,3);
}
P=mul(P,pow_mod(pre[cnt],n-tmp+1),3,3,3);
st=mul(st,P,3,3,1);
printf("%lld\n",st.m[1][1]);
return 0;
}