最小环问题

          最小环问题

(摘自 qyf 童鞋的博客 :http://www.cnblogs.com/wsdestdq/p/6719826.html  )

最小环问题是指:在图中找出一个环,并使该环上边的权值和最小

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 9999;
int n, m, u, v, w, ans;
int g[maxn][maxn], dis[maxn][maxn];

int main() {
    cin >> n >> m;
    for(int i = 1; i <= n; i++)     //初始化
        for(int j = 1; j <= n; j++)
            g[i][j] = maxn;
    for(int i = 1; i <= m; i++) {     //双向图
        cin >> u >> v >> w;
        g[u][v] = w;
        g[v][u] = w;
    }
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            dis[i][j] = g[i][j];
    ans = maxn;
    for(int k = 1; k <= n; k++) {     //Floyed算法
        for(int i = 1; i <= n-1; i++)
            for(int j = i+1; j <= n-1; j++)
                ans=min(ans, dis[i][j]+g[i][k]+g[k][j]);      //找最小值
        for(int i = 1; i <= n; i++)     //松弛
            for(int j = 1; j <= n; j++)
                dis[i][j] = min(dis[i][j], dis[i][k]+dis[k][j]);
    }
    cout << ans << endl;
    return 0;
}

 

posted @ 2018-04-06 17:18  落云小师妹  阅读(231)  评论(0编辑  收藏  举报