Problem Description
杭州有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)。
接下来的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算法求解即可;
易错:1.ans=max(map[i][j]+g[i][k]+g[j][k], ans) 中map[i][j]为最短路,g[i][j]为原始数据;
2.求解ans时要特判i!=j以防ans被赋值为零。
AC代码:
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; int g[110][110], n, m, ans, map[110][110]; int main(void){ while(cin >> n >> m){ ans=214748364; for(int i=1; i<=n; i++){ for(int j=1; j<=n; j++) map[i][j]=g[i][j]=214748364; map[i][i]=g[i][i]=0; } for(int i=1; i<=m; i++){ int x, y,z ; cin >> x >> y >> z; map[x][y]=map[y][x]=g[x][y]=g[y][x]=min(g[x][y], z); } for(int k=1; k<=n; k++){ for(int i=1; i<k; i++) for(int j=1; j<k; j++) /*2-------*/ if(i!=j) ans=min(map[i][j]+g[j][k]+g[i][k], ans);/*-------1*/ for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) map[i][j]=min(map[i][j], map[i][k]+map[k][j]); } if(ans<214748364) cout << ans << endl; else cout << "It's impossible." << endl; } }