procedure2012
It's not worth it to know you're not worth it!

[关键字]:矩阵加速 递推

[题目大意]:http://221.192.240.123:8586/JudgeOnline/showproblem?problem_id=1673

//=====================================================================================================

[分析]:其实就可以一个一个的除,求出的余数和下一个数连起来就是下一个要除的数:f[i]=f[i-1]*10k+i,f[i]是前i个数连起来时的余数,k是第i个数的位数。这个递推式是O(n)的回超时,但可以用矩阵乘法+快速幂加速O(logn)解决,至于矩阵的构造会的不用说,不会的还是自己学学在自己想吧。

[代码]:

View Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;

struct node
{
int n,m,dat[4][4];
}ans,g;
long long n,ten,num;
int mod;

node Cheng(node a,node b)
{
node c;
long long temp;
c.n=a.n,c.m=b.m;
for (int i=1;i<=a.n;i++)
for (int j=1;j<=b.m;j++)
{
temp=0;
for (int k=1;k<=a.m;k++)
{
temp+=(long long)a.dat[i][k]*b.dat[k][j];
if (temp>=mod) temp%=mod;
}
c.dat[i][j]=temp;
}
return c;
}

void Solve()
{
ans.n=1,ans.m=3;
ans.dat[1][1]=0,ans.dat[1][2]=0,ans.dat[1][3]=1;
g.n=3,g.m=3;
ten=1;
do{
ten*=10;
num=min(ten-1,n)-ten/10+1;
memset(g.dat,0,sizeof(g.dat));
g.dat[1][1]=ten%mod;
g.dat[2][1]=g.dat[2][2]=g.dat[3][1]=g.dat[3][2]=g.dat[3][3]=1;
// printf("%d\n",num);
while (1)
{
if (num&1) ans=Cheng(ans,g);
num>>=1;if (!num) break;
g=Cheng(g,g);
// printf("%d\n",num);
}
}while (ten<=n);
printf("%d\n",ans.dat[1][1]);
}

int main()
{
scanf("%lld%d",&n,&mod);
Solve();
system("pause");
return 0;
}



posted on 2012-02-16 13:54  procedure2012  阅读(590)  评论(0编辑  收藏  举报