您的位置:首页 > 其它

hdu 2254 矩阵的应用

2013-03-02 13:19 190 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2254

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

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

View Code

#include<iostream>
#include<map>
#include<cstring>
const int N=31;
const int m=2008;
using namespace std;
int n,len;
struct Matrix{
int map

;
};

Matrix mat[10001];
map<int,int>mp;

Matrix Mul(Matrix &a,Matrix &b){
Matrix c;
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
c.map[i][j]=0;
for(int k=0;k<len;k++){
c.map[i][j]+=a.map[i][k]*b.map[k][j];
c.map[i][j]%=m;
}
}
}
return c;
}
/*
Matrix Pow(int n){
if(n==1)return mat[0];
else if(n&1){
return Mul(mat[0],Pow(n-1));
}else {
Matrix temp=Pow(n>>1);
return Mul(temp,temp);
}
}
*/

int main(){
while(scanf("%d",&n)!=EOF){
memset(mat[0].map,0,sizeof(mat[0].map));
mp.clear();
int p1,p2,k;
len=0;
while(n--){
scanf("%d%d",&p1,&p2);
if(mp.find(p1)==mp.end()){
mp[p1]=len++;
}
if(mp.find(p2)==mp.end()){
mp[p2]=len++;
}
mat[0].map[mp[p1]][mp[p2]]++;
}
for(int i=1;i<10001;i++){
mat[i]=Mul(mat[i-1],mat[0]);
}
scanf("%d",&k);
int v1,v2,t1,t2;
while(k--){
scanf("%d%d%d%d",&v1,&v2,&t1,&t2);
if(mp.find(v1)==mp.end()||mp.find(v2)==mp.end()){
printf("0\n");
continue;
}
int ans=0;
for(int i=t1-1;i<t2;i++){
ans+=mat[i].map[mp[v1]][mp[v2]];
}
printf("%d\n",ans%m);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: