【题目链接】
【算法】
弗洛伊德求最小环模板
我们知道,在一个环上,一定有一个有且仅有一个编号最大的点,设这个点为k,起点为i,终点为j,那么
mincost = dist[i][j] + cost[j][k] + cost[k][i] (dist[i][j]为i到j的最短路)
所以只需枚举i,j,k,在计算最短路的同时,计算最小环,即可
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 110 const int INF = 1e8; int i,j,n,m,a,b,c; int g[MAXN][MAXN],mp[MAXN][MAXN]; inline void floyd() { int i,j,k,ans = INF; for (k = 1; k <= n; k++) { for (i = 1; i < k; i++) { for (j = i + 1; j < k; j++) { ans = min(ans,g[i][j]+mp[j][k]+mp[k][i]); } } for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { g[i][j] = min(g[i][j],g[i][k]+g[k][j]); } } } if (ans == INF) puts("It's impossible."); else printf("%d ",ans); } int main() { while (scanf("%d%d",&n,&m) != EOF) { for (i = 0; i <= n; i++) { for (j = 0; j <= n; j++) { g[i][j] = mp[i][j] = INF; } } for (i = 1; i <= m; i++) { scanf("%d%d%d",&a,&b,&c); g[a][b] = mp[a][b] = min(g[a][b],c); g[b][a] = mp[b][a] = min(g[b][a],c); } floyd(); } return 0; }