杭州有N个景区,景区之间有一些双向的路来连接,现在8600想找一条旅游路线,这个路线从A点出发并且最后回到A点,假设经过的路线为V1,V2,….VK,V1,那么必须满足K>2,就是说至除了出发点以外至少要经过2个其他不同的景区,而且不能重复经过同一个景区。现在8600需要你帮他找一条这样的路线,并且花费越少越好。
Input
第一行是2个整数N和M(N <= 100, M <= 1000),代表景区的个数和道路的条数。
接下来的M行里,每行包括3个整数a,b,c.代表a和b之间有一条通路,并且需要花费c元(c <= 100)。
Output
对于每个测试实例,如果能找到这样一条路线的话,输出花费的最小值。如果找不到的话,输出”It’s impossible.”.
Sample Input
3 3
1 2 1
2 3 1
1 3 1
3 3
1 2 1
1 2 3
2 3 1
Sample Output
3
It’s impossible.
分析:
这是一个最短路中的最小环问题, 利用Floyd算法
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <string.h>
#define INF 0x3f3f3f
using namespace std;
int Map[101][101];
int dist[101][101];
int ans;
int n,m;
void floyd()
{
int i,j,k;
for (k=1; k<=n; k++)
{
for (i=1; i<=n; i++)
{
for (j=1; j<=n; j++)
{
if (i!=j&&i!=k&&j!=k&&ans>dist[i][j]+Map[i][k]+Map[k][j])
ans = dist[i][j]+Map[i][k]+Map[k][j];
}
}
for (i=1; i<=n; i++)
{
for (j=1; j<=n; j++)
{
if (dist[i][j]>dist[i][k]+dist[k][j])
dist[i][j] = dist[i][k]+dist[k][j];
}
}
}
}
int main()
{
int i,j;
while (cin>>n>>m)
{
for (i=1; i<=n; i++)
{
for (j=1; j<=n; j++)
{
if (i==j)
{
Map[i][j] = 0;
dist[i][j]=0;
}
else
{
Map[i][j] = INF;
dist[i][j]=INF;
}
}
}
for (i=0; i<m; i++)
{
ans = INF;
int a,b,c;
cin>>a>>b>>c;
if (c<Map[a][b])
{
Map[a][b]=Map[b][a]=c;
dist[a][b]=dist[b][a]=c;
}
}
floyd();
if (ans!=INF)
cout<<ans<<endl;
else
cout<<"It's impossible."<<endl;
}
return 0;
}