How many ways??(HDU 2157)

How many ways??

Sample Input

4 4  //n个点,m条路径
0 1  //s->t可通
0 2
1 3
2 3
2  //询问数
0 3 2  //从0到3走两条路可到的方案有多少种
0 3 3
3 6
0 1
1 0
0 2
2 0
1 2
2 1
2
1 2 1
0 1 3
0 0

 

Sample Output
2
0
1
3
 
矩阵快速幂,在离散数学课例听过类似的题目,n次幂就代表n条路方案。
 1 #include <cstring>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <iostream>
 5 using namespace std;
 6 typedef long long LL;
 7 struct Matrix
 8 {
 9     LL mat[25][25];
10 }p;
11 int n,m;
12 int t,a,b,k;
13 Matrix mul(Matrix a,Matrix b)
14 {
15     Matrix c;
16     for(int i=0;i<n;i++)
17     {
18         for(int j=0;j<n;j++)
19         {
20             c.mat[i][j]=0;
21             for(int k=0;k<n;k++)
22                 c.mat[i][j]=(c.mat[i][j]+a.mat[i][k]*b.mat[k][j])%1000;
23         }
24     }
25     return c;
26 }
27 Matrix mod_pow(Matrix x,int n)
28 {
29     Matrix res;
30     memset(res.mat,0,sizeof(res.mat));
31     for(int i=0;i<25;i++)
32         res.mat[i][i]=1;
33     while(n)
34     {
35         if(n&1)
36             res=mul(res,x);
37         x=mul(x,x);
38         n>>=1;
39     }
40     return res;
41 }
42 int main()
43 {
44     freopen("in.txt","r",stdin);
45     while(cin>>n>>m)
46     {
47         if(n==0&&m==0)
48             break;
49         memset(p.mat,0,sizeof(p.mat));
50         int s,t;
51         for(int i=0;i<m;i++)
52         {
53             cin>>s>>t;
54             p.mat[s][t]=1;
55         }
56         cin>>t;
57         while(t--)
58         {
59             cin>>a>>b>>k;
60             Matrix ans=mod_pow(p,k);
61         /*    for(int i=0;i<n;i++)
62             {
63                 for(int j=0;j<n;j++)
64                     cout<<ans.mat[i][j]<<" ";
65                 cout<<endl;
66             }*/
67             cout<<ans.mat[a][b]<<endl;
68         }
69     }
70     return 0;
71 }

 

posted @ 2016-05-06 10:34  御心飞行  阅读(506)  评论(0编辑  收藏  举报