Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1
思路:弗洛伊德算法。三层for循环。
代码:
#include <stdio.h>
#include <string.h>
#include
#include
#include
#include
#include
#include
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const int inf=1<<29;
int main()
{
int map[210][210],n,m,a,b,x,s,t;
while(~scanf("%d %d",&n,&m))
{
if(n0&&m0)break;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
map[i][j]=0;
else
map[i][j]=inf;
}
}
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&a,&b,&x);
if(x<map[a][b])
{
map[a][b]=x;
map[b][a]=x;
}
}
scanf("%d %d",&s,&t);
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(map[i][k]+map[k][j]<map[i][j])
{
map[i][j]=map[i][k]+map[k][j];
}
}
}
}
if(map[s][t]==inf)printf("%d\n",-1);
else
{
printf("%d\n",map[s][t]);
}
}
return 0;
}
畅通工程续
最新推荐文章于 2023-03-05 19:49:16 发布