hdu 2157 How many ways?? (矩阵快速幂经典题目)
题意:给定一个有向图,问从A点恰好走k步(允许重复经过边)到达B点的方案数mod p的值
思路: ** 把给定的图转为邻接矩阵,即A(i,j)=1当且仅当存在一条边i->j。令C=A*A,那么C(i,j)=ΣA(i,k)A(k,j),实际上就等于从点i到点j恰好经过2条边的路径数(枚举k为中转点)。类似地,CA的第i行第j列就表示从i到j经过3条边的路径数。同理,如果要求经过k步的路径数,我们只需要快速幂求出A^k即可。**
这个转化好美啊。。。
1/* ***********************************************
2Author :111qqz
3Created Time :Wed 19 Oct 2016 08:14:56 PM CST
4File Name :code/hdu/2157.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=25;
34const int mod = 1000;
35int n,m;
36struct Mat
37{
38 int mat[N][N];
39 void clear()
40 {
41 ms(mat,0);
42 }
43}M;
44
45Mat operator * (Mat a,Mat b)
46{
47 Mat ans;
48 ans.clear();
49 for ( int i = 0 ; i < n ; i++)
50 for ( int j = 0 ; j < n ;j++)
51 for ( int k = 0 ; k < n ; k++)
52 ans.mat[i][j] = (ans.mat[i][j] + a.mat[i][k] * b.mat[k][j])%mod;
53
54 return ans;
55}
56
57Mat operator ^ (Mat a,int b)
58{
59 Mat ans;
60 ans.clear();
61 for ( int i = 0 ; i < n ; i++) ans.mat[i][i] = 1;
62
63 while (b>0)
64 {
65 if (b&1) ans = ans * a;
66 b = b >> 1LL;
67 a = a* a;
68 }
69 return ans;
70}
71LL ksm( LL a,LL b, LL k)
72{
73 LL res = 1LL;
74 while (b)
75 {
76 if (b&1) res = (res * a) % k;
77 b = b >> 1LL;
78 a = ( a * a) % k;
79 }
80 return res;
81}
82int main()
83{
84 #ifndef ONLINE_JUDGE
85 freopen("code/in.txt","r",stdin);
86 #endif
87
88 while (~scanf("%d%d",&n,&m))
89 {
90 if (n==0&&m==0) break;
91 M.clear();
92 for ( int i = 1 ; i <= m ; i ++)
93 {
94 int s,t;
95 scanf("%d %d",&s,&t);
96 M.mat[s][t] = 1;
97 }
98
99 int T;
100 scanf("%d",&T);
101 while (T--)
102 {
103 int a,b,k;
104 scanf("%d%d%d",&a,&b,&k);
105 Mat ans;
106 ans.clear();
107 ans = M ^ k;
108 printf("%d\n",ans.mat[a][b]);
109 }
110 }
111
112 #ifndef ONLINE_JUDGE
113 fclose(stdin);
114 #endif
115 return 0;
116}