hdu 2157 How many ways?? ( 经典矩阵 )

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2157

题解链接:http://blog.csdn.net/rowanhaoa/article/details/21134509

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<stdlib.h>
 5 
 6 using namespace std;
 7 
 8 const int mod=1e3;
 9 
10 typedef struct matrix
11 {
12     int  tr[25][25];
13     matrix (){ memset(tr,0,sizeof(tr)); }
14 }S;
15 int n,m,map[25][25];
16 
17 S mul( S A, S B)
18 {
19     S C;
20     for(int i=1;i<=n;i++)
21         for(int j=1;j<=n;j++)
22             for(int k=1;k<=n;k++)
23             C.tr[i][j]=(C.tr[i][j]+A.tr[i][k]*B.tr[k][j])%mod;
24     return C;
25 }
26 
27 S mulpow( S A, int k )
28 {
29     S B;
30     if( k == 1 || k== 0 ) return A;
31     B = mulpow( A, k/2 );
32     if( k%2 == 0 )
33         return mul( B, B );
34 
35     return mul( A, mul( B, B ));
36 }
37 //
38 //S mulpow( S A, int k )
39 //{
40 //    S B;
41 //    for(int i=1;i<=n;i++)
42 //        B.tr[i][i]=1;
43 //    while( k )
44 //    {
45 //        if( k&1 ) B = mul( B, A );
46 //        A = mul( A, A );
47 //        k >>=1;
48 //    }
49 //    return B;
50 //}
51 
52 int main( )
53 {
54     int a,b,c;
55     while(scanf("%d%d",&n,&m),n||m)
56     {
57     S t,t1;
58         for(int i=1;i<=m;i++)
59         {
60             scanf("%d%d",&a,&b);
61             t.tr[a+1][b+1]=1;
62         }
63         scanf("%d",&m);
64         for(int i=1;i<=m;i++)
65         {
66             scanf("%d%d%d",&a,&b,&c);
67             if( a==b && c==0 )
68             {
69                 printf("1\n");
70                 continue;
71             }
72             if( a!=b && c==0 )
73             {
74                 printf("0\n");
75                 continue;
76             }
77             t1 = mulpow( t, c );
78             printf("%d\n",(t1.tr[a+1][b+1])%mod);
79         }
80     }
81     return 0;
82 }
View Code

 

posted @ 2014-04-02 17:26  lysr__tlp  阅读(175)  评论(0编辑  收藏  举报