您的位置:首页 > 其它

hdu 2807 The Shortest Path(矩阵+floyd)

2015-08-17 18:05 267 查看
[align=left]Problem Description[/align]

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?


[align=left]Input[/align]

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].


[align=left]Output[/align]

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".


[align=left]Sample Input[/align]

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


[align=left]Sample Output[/align]

1
Sorry


[align=left]Source[/align]
HDU 2009-4 Programming Contest

此题要先找出哪些城市可以连边,可以通过矩阵相乘来实现,得出的矩阵与第三个矩阵比较,看看是否可以连边。
算出所有edge后,再通过floyd来算出任意两个城市的最短距离。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<set>
using namespace std;
#define inf 1<<26
#define N 86
int n,m;
int edge

;
struct Matrix
{
int mp

;
}matrix
;
Matrix Mul(Matrix a,Matrix b)
{
Matrix res;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=m;j++)
{
res.mp[i][j]=0;
for(int k=1;k<=m;k++)
{
res.mp[i][j]=res.mp[i][j]+(a.mp[i][k]*b.mp[k][j]);
}
}
}
return res;
}
bool judge(Matrix a,Matrix b)
{
for(int i=1;i<=m;i++)
{
for(int j=1;j<=m;j++)
{
if(a.mp[i][j]!=b.mp[i][j])
return false;
}
}
return true;
}
void init()
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==j)
edge[i][j]=0;
else
{
edge[i][j]=inf;
}
}
}
}
void floyd()
{
for(int k=1;k<=n;k++)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(edge[i][j]>edge[i][k]+edge[k][j])
edge[i][j]=edge[i][k]+edge[k][j];
}
}
}
}
int main()
{
while(scanf("%d%d",&n,&m)==2 && n+m)
{
//memset(edge,0,sizeof(edge));

init();

for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
for(int k=1;k<=m;k++)
{
scanf("%d",&matrix[i].mp[j][k]);
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==j)
continue;
Matrix tmp = Mul(matrix[i],matrix[j]);
for(int k=1;k<=n;k++)
{
if(i==k || j==k)
continue;
if(judge(tmp,matrix[k]))
edge[i][k]=1;
}
}
}

floyd();

int c;
scanf("%d",&c);
while(c--)
{
int u,v;
scanf("%d%d",&u,&v);
if(edge[u][v]!=inf)
printf("%d\n",edge[u][v]);
else
printf("Sorry\n");
}
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: