校赛A题矩阵幂解图论中长度为K的路径的数_zzzloveGrain的空间_百度空间


A non-negative interger is a K satisfied number
if and only if this interger does not exist two adjacent
digits, the absolute value of the difference between them
is greater than K.

For example:
0, 2, 5, 36 and 236 are 3 satisfied number, and are 4 satisfied number too.
but 237 is not a 3 satisfied number, while it is a 4 satisfied number,
for its second digit is 3 and its third digit is 7,
and the absolute value of the difference between 3 and 7 is 4,
which is greater than 3.

Now give two interger N and K.
Please tell me how many K satisfied numbers there are for all
the N-digit numbers (can not have leading 0).
Because the result may be very large,
we make the result module 2008512 for the output.



The input contains many test cases.
For each test case, the input contains only one line
with two integers N ( 1 <= N <= 10^9 ) and K ( 0 <= K <= 9 ).



For each test case output the answer on a single line.



1 1
2 0
5423 8
3243421 5
2 1



10
9
260649
1928206
26

考虑这样一个图g,节点为0、1、2、3、4、5、6、7、8、9。若|i-j|<=m,g[i][j]=1;当n大于1时,矩阵的n-1次幂中的每个元素都是对应n个节点的一条路径,每个元素的值是这个路径的走法个数。(考虑矩阵的乘法的性质。)这道题就迎刃而解了。注意n==1时,要特殊处理,以及数是没有前导零的。

#include<stdio.h>
#include<string.h>
const int mod=2008512;
int abs(int a){return a>0?a:-a;}
struct Matrix
{
       int a[10][10];
       Matrix operator *(Matrix &l)
       {
              Matrix temp;
              memset(temp.a,0,sizeof(temp.a));
              for(int i=0;i<10;i++)
                  for(int j=0;j<10;j++)
                     for(int k=0;k<10;k++)
                          temp.a[i][j]=(temp.a[i][j]+(int)(((a[i][k]%mod)*(long long)(l.a[j][k]))%mod))%mod;
              return temp;
       }
}M;
Matrix pow(Matrix &t,int k)
{
       Matrix temp;
       if(k==1) return t;
       temp=t*t;
       if(k&1) return pow(temp,k/2)*t;
       return pow(temp,k/2);
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
          if(n==1)
          {
                  puts("10");
                  continue;
          }
          for(int i=0;i<10;i++)
              for(int j=0;j<10;j++)
                   if(abs(i-j)<=m) M.a[i][j]=1;
                   else M.a[i][j]=0;
          Matrix temp=pow(M,n-1);
          int ans=0;
          for(int i=1;i<10;i++)
              for(int j=0;j<10;j++)
                  ans=(ans+temp.a[i][j])%mod;
          printf("%d\n",ans);
    }
}



郑重声明:资讯 【校赛A题矩阵幂解图论中长度为K的路径的数_zzzloveGrain的空间_百度空间】由 发布,版权归原作者及其所在单位,其原创性以及文中陈述文字和内容未经(企业库qiyeku.com)证实,请读者仅作参考,并请自行核实相关内容。若本文有侵犯到您的版权, 请你提供相关证明及申请并与我们联系(qiyeku # qq.com)或【在线投诉】,我们审核后将会尽快处理。
—— 相关资讯 ——