题目链接:hdu 2807 The Shortest Path
题意:
如果矩阵A*B=C,那么就表示A-->B有一条单向路径,距离为1.
给一些矩阵,然后问任意两个矩阵直接的距离。
题解:
把矩阵读进来后处理一下邻接矩阵,然后Folyd一下。
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #define mst(a,b) memset(a,b,sizeof(a)) 5 #define F(i,a,b) for(int i=a;i<=b;++i) 6 7 using namespace std; 8 typedef long long ll; 9 10 const int mat_N=100,INF=1e9;//矩阵阶数,取膜 11 int n,m,q,mp[100][100]; 12 struct mat{ 13 int c[mat_N][mat_N]; 14 void init(){mst(c,0);} 15 mat operator*(mat b){ 16 mat M;int N=m-1;M.init(); 17 F(i,0,N)F(j,0,N)if(c[i][j])F(k,0,N)M.c[i][k]=M.c[i][k]+c[i][j]*b.c[j][k]; 18 return M; 19 } 20 }A[91],tmp; 21 22 int check(mat &a,mat &b) 23 { 24 F(i,0,m-1)F(j,0,m-1)if(a.c[i][j]!=b.c[i][j])return 0; 25 return 1; 26 } 27 28 int main(){ 29 while(scanf("%d%d",&n,&m),n+m) 30 { 31 F(i,1,n)F(j,0,m-1)F(k,0,m-1)scanf("%d",&A[i].c[j][k]); 32 F(i,1,n)F(j,1,n)mp[i][j]=INF; 33 F(i,1,n)F(j,1,n)if(i!=j) 34 { 35 tmp=A[i]*A[j]; 36 F(k,1,n)if(j!=k&&k!=i) 37 if(check(tmp,A[k]))mp[i][k]=1; 38 } 39 F(k,1,n)F(i,1,n)if(mp[i][k]!=INF)F(j,1,n)if(mp[k][j]!=INF)mp[i][j]=min(mp[i][j],mp[i][k]+mp[k][j]); 40 scanf("%d",&q); 41 while(q--) 42 { 43 int x,y; 44 scanf("%d%d",&x,&y); 45 mp[x][y]==INF?puts("Sorry"):printf("%d ",mp[x][y]); 46 } 47 } 48 return 0; 49 }