The Shortest Path
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3008 Accepted Submission(s): 988
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?
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
思路:暴力枚举所有AB,然后建图。最后跑一次floyd就可以了。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define N 100
#define INF 100000000
int n,m;
int city[N][N][N];
int ma[N][N];
int ans[N][N];
void in()
{
for(int k=1; k<=n; k++)
for(int i=1; i<=m; i++)
for(int j=1; j<=m; j++)
scanf("%d",&city[k][i][j]);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
ma[i][j]=INF;
}
void matrix(int a,int b)
{
memset(ans,0,sizeof(ans));
for(int i=1; i<=m; i++)
for(int j=1; j<=m; j++)
for(int k=1; k<=m; k++)
ans[i][j]+=city[a][i][k]*city[b][k][j];
for(int i=1;i<=n;i++)
{
if(i==a||i==b) continue;
int flag=0;
for(int j=1;j<=m;j++)
for(int k=1;k<=m;k++)
if(ans[j][k]!=city[i][j][k]) {flag=1;break;}
if(!flag) ma[a][i]=1;
}
}
void make_map()
{
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
if(i==j) continue;
matrix(i,j);
}
}
void floyd()
{
for(int k=1; k<=n; k++)
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
ma[i][j]=min(ma[i][j],ma[i][k]+ma[k][j]);
}
int main()
{
int t,s,e;
while(~scanf("%d %d",&n,&m)&&n)
{
in();
make_map();
floyd();
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&s,&e);
if(ma[s][e]==INF) printf("Sorry\n");
else printf("%d\n",ma[s][e]);
}
}
return 0;
}