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即可。**

M67_十个利用矩阵乘法解决的经典题目

这个转化好美啊。。。

/* ***********************************************
Author :111qqz
Created Time :Wed 19 Oct 2016 08:14:56 PM CST
File Name :code/hdu/2157.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6const int N=25;
 7const int mod = 1000;
 8int n,m;
 9struct Mat
10{
11    int mat[N][N];
12    void clear()
13    {
14	ms(mat,0);
15    }
16}M;
1Mat operator * (Mat a,Mat b)
2{
3    Mat ans;
4    ans.clear();
5    for ( int i = 0 ; i < n ; i++)
6	for ( int j = 0 ; j < n ;j++)
7	    for ( int k = 0 ; k < n ; k++)
8		ans.mat[i][j] = (ans.mat[i][j] + a.mat[i][k] * b.mat[k][j])%mod;
    return ans;
}
1Mat operator ^ (Mat a,int b)
2{
3    Mat ans;
4    ans.clear();
5    for ( int i = 0 ; i < n ; i++) ans.mat[i][i] = 1;
 1    while (b>0)
 2    {
 3	if (b&1) ans = ans * a;
 4	b = b >> 1LL;
 5	a = a* a;
 6    }
 7    return ans;
 8}
 9LL ksm( LL a,LL b, LL k)
10{
11    LL res = 1LL;
12    while (b)
13    {
14	if (b&1) res = (res * a) % k;
15	b = b >> 1LL;
16	a = ( a * a) % k;
17    }
18    return res;
19}
20int main()
21{
22	#ifndef  ONLINE_JUDGE 
23	freopen("code/in.txt","r",stdin);
24  #endif
 1	while (~scanf("%d%d",&n,&m))
 2	{
 3	    if (n==0&&m==0) break;
 4	    M.clear();
 5	    for ( int i = 1 ; i <= m ; i ++)
 6	    {
 7		int s,t;
 8		scanf("%d %d",&s,&t);
 9		M.mat[s][t] = 1;
10	    }
 1	    int T;
 2	    scanf("%d",&T);
 3	    while (T--)
 4	    {
 5		int a,b,k;
 6		scanf("%d%d%d",&a,&b,&k);
 7		Mat ans;
 8		ans.clear();
 9		ans = M ^ k;
10		printf("%d\n",ans.mat[a][b]);
11	    }
12	}
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}