题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2807
The Shortest Path
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3234 Accepted Submission(s): 1066
Problem Description
There are N cities in the country. Each city is represent by a matrix size of M*M. If city A, B and C satisfy that A*B = C, we say that there is a road from A to C with distance 1 (but that does not means there is a road from C to A).
Now the king of the country wants to ask me some problems, in the format:
Is there is a road from city X to Y?
I have to answer the questions quickly, can you help me?
Input
Each test case contains a single integer N, M, indicating the number of cities in the country and the size of each city. The next following N blocks each block stands for a matrix size of M*M. Then a integer K means the number of questions the king will ask, the following K lines each contains two integers X, Y(1-based).The input is terminated by a set starting with N = M = 0. All integers are in the range [0, 80].
Output
For each test case, you should output one line for each question the king asked, if there is a road from city X to Y? Output the shortest distance from X to Y. If not, output “Sorry”.
Sample Input
3 2
1 1
2 2
1 1
1 1
2 2
4 4
1
1 3
3 2
1 1
2 2
1 1
1 1
2 2
4 3
1
1 3
0 0
Sample Output
1
Sorry
【中文题意】每个城市由一个矩阵来代表,任意三个城市(不同的三个城市),假如A* B=C,即A和B两个城市的矩阵相乘等于C矩阵,那么认为A、C两个城市是连通的(单向联通,即只能从A到C),且其之间的距离为1。根据以上条件建立关系矩阵,然后再跑一遍Floyed算法。注意时间复杂度N^6是过不了的,降到了N^5次方左右。
【AC代码】
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
int n,m;
int a[82][82][82],dis[82][82],c[82][82];
void init(int a[82][82],int b[82][82])
{
memset(c,0,sizeof(c));
for(int i=1; i<=m; i++)
{
for(int j=1; j<=m; j++)
{
for(int k=1; k<=m; k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
}
bool judge(int b[82][82])
{
for(int i=1; i<=m; i++)
{
for(int j=1; j<=m; j++)
{
if(b[i][j]!=c[i][j])
{
return false;
}
}
}
return true;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
if(n==0&&m==0)
{
break;
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
for(int k=1; k<=m; k++)
{
scanf("%d",&a[i][j][k]);
}
}
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
dis[i][j]=INF;
}
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(i!=j)
{
init(a[i],a[j]);
for(int k=1; k<=n; k++)
{
if(i!=k&&k!=j&&i!=j)
if(judge(a[k]))
{
dis[i][k]=1;
}
}
}
}
}
for(int k=1; k<=n; k++)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(dis[i][j]+dis[j][k]<dis[i][k])
{
dis[i][k]=dis[i][j]+dis[j][k];
}
}
}
}
int k,u,v;
scanf("%d",&k);
for(int i=0; i<k; i++)
{
scanf("%d%d",&u,&v);
if(dis[u][v]!=INF)
{
printf("%d\n",dis[u][v]);
}
else
{
printf("Sorry\n");
}
}
}
return 0;
}