Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1912 Accepted Submission(s): 692
解题思路:
这道题就是模板题,图论中有一个结论就是说,我现在有一个n个顶点构成的邻接矩阵,那么我们要得到某个顶点救过k条路径到达某个顶点的方案数目,其实就是所说的矩阵的快速幂了。输出经过k次幂后的邻接矩阵。
1 # include<iostream> 2 # include<cstdio> 3 # include<cstring> 4 5 using namespace std; 6 7 int n,m; 8 9 struct matrix 10 { 11 int p[25][25]; 12 }; 13 14 struct matrix multi( matrix a,matrix b )//连个矩阵相乘 15 { 16 matrix c; 17 for( int i=0;i<n;i++ ) 18 { 19 for( int j=0;j<n;j++ ) 20 { 21 c.p[i][j]=0; 22 for( int k=0;k<n;k++ ) 23 c.p[i][j]=(c.p[i][j]+a.p[i][k]*b.p[k][j])%1000; 24 } 25 } 26 27 return c; 28 } 29 30 matrix My_power( matrix a, int k ) 31 { 32 33 matrix b; 34 for( int i=0;i<n;i++) 35 for( int j=0;j<n;j++) 36 if( i==j ) 37 b.p[i][j]=1; 38 else 39 b.p[i][j]=0; 40 while( k ) 41 { 42 if(k%2==1) 43 b=multi(b,a); 44 k=k/2; 45 a=multi(a,a); 46 } 47 return b; 48 } 49 50 int main(void) 51 { 52 int S,E,k; 53 matrix a,b; 54 while(scanf("%d%d",&n,&m)!=EOF&&(n!=0||m!=0)) 55 { 56 memset(a.p,0,sizeof(a.p)); 57 for( int i=0;i<m;i++) 58 { 59 int x1,x2; 60 scanf("%d%d",&x1,&x2); 61 a.p[x1][x2]=1; 62 } 63 int T; scanf("%d",&T); 64 while(T--) 65 { 66 scanf("%d%d%d",&S,&E,&k); 67 b = My_power(a,k); 68 while( b.p[S][E] < 0 )//以后碰到取模的情况记得添加 69 b.p[S][E] += 1000; 70 printf("%d\n",b.p[S][E]); 71 } 72 } 73 return 0; 74 }
代码: