hdu 2254 矩阵的应用

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

题意:有向图中求A点到B点路径长度为t1~t2的路径总数

离散数学中,有向图的邻接矩阵A表示所有点之间路径长度为1的路径数量,A^n则表示路径长度为n的路径数量,故需要求某两点在(A^t1)~(A^t2)的路径数量之和

View Code
 1 #include<iostream>
 2 #include<map>
 3 #include<cstring>
 4 const int N=31;
 5 const int m=2008;
 6 using namespace std;
 7 int n,len;
 8 struct Matrix{
 9     int map[N][N];
10 };
11 
12 Matrix mat[10001];
13 map<int,int>mp;
14 
15 Matrix Mul(Matrix &a,Matrix &b){
16     Matrix c;
17     for(int i=0;i<len;i++){
18         for(int j=0;j<len;j++){
19             c.map[i][j]=0;
20             for(int k=0;k<len;k++){
21                 c.map[i][j]+=a.map[i][k]*b.map[k][j];
22                 c.map[i][j]%=m;
23             }
24         }
25     }
26     return c;
27 }
28 /*
29 Matrix Pow(int n){
30     if(n==1)return mat[0];
31     else if(n&1){
32         return Mul(mat[0],Pow(n-1));
33     }else {
34         Matrix temp=Pow(n>>1);
35         return Mul(temp,temp);
36     }
37 }
38 */
39 
40 int main(){
41     while(scanf("%d",&n)!=EOF){
42         memset(mat[0].map,0,sizeof(mat[0].map));
43         mp.clear();
44         int p1,p2,k;
45         len=0;
46         while(n--){
47             scanf("%d%d",&p1,&p2);
48             if(mp.find(p1)==mp.end()){
49                 mp[p1]=len++;
50             }
51             if(mp.find(p2)==mp.end()){
52                 mp[p2]=len++;
53             }
54             mat[0].map[mp[p1]][mp[p2]]++;
55         }
56         for(int i=1;i<10001;i++){
57             mat[i]=Mul(mat[i-1],mat[0]);
58         }
59         scanf("%d",&k);
60         int v1,v2,t1,t2;
61         while(k--){
62             scanf("%d%d%d%d",&v1,&v2,&t1,&t2);
63             if(mp.find(v1)==mp.end()||mp.find(v2)==mp.end()){
64                 printf("0\n");
65                 continue;
66             }
67             int ans=0;
68             for(int i=t1-1;i<t2;i++){
69                 ans+=mat[i].map[mp[v1]][mp[v2]];
70             }
71             printf("%d\n",ans%m);
72         }
73     }
74     return 0;
75 }
原文地址:https://www.cnblogs.com/wally/p/2939976.html