signed

QiShunwang

“诚信为本、客户至上”

观光之旅(floyd求权值最小环)

2021/3/21 0:12:30   来源:
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110, INF = 0x3f3f3f3f;
int n, m;
int d[N][N], g[N][N];
int pos[N][N];
int path[N], cnt;
void get_path(int i, int j)
{
    if (pos[i][j] == 0) return;
    int k = pos[i][j];
    get_path(i, k);
    path[cnt ++ ] = k;
    get_path(k, j);
}
int main()
{
    cin >> n >> m;
    memset(g, 0x3f, sizeof g);
    for (int i = 1; i <= n; i ++ ) g[i][i] = 0;
    while (m -- )
    {
        int a, b, c;
        cin >> a >> b >> c;
        g[a][b] = g[b][a] = min(g[a][b], c);
    }
    int res = INF;
    memcpy(d, g, sizeof d);
    //floyd表示d[k][i][j]在不经过编号大于k的结点i,j之间最近距离
    //最小环分成n类,每类表示环上的点不超过k
    for (int k = 1; k <= n; k ++ )
    {
        //此时d[i][j]表示在不经过编号大于k-1的结点i,j之间最近距离
        for (int i = 1; i <k; i ++ )
            for (int j = i + 1;j<k; j ++ )
                if ((long long)d[i][j] + g[j][k] + g[k][i] < res)
                //环i->k->j->i
                {
                    res = d[i][j] + g[j][k] + g[k][i];
                    cnt = 0;
                    path[cnt ++ ] = k;
                    path[cnt ++ ] = i;
                    get_path(i, j);
                    path[cnt ++ ] = j;
                }
        for (int i = 1; i <= n; i ++ )
            for (int j = 1; j <= n; j ++ )
                if (d[i][j] > d[i][k] + d[k][j])
                {
                    d[i][j] = d[i][k] + d[k][j];
                    pos[i][j] = k;
                }
    }
    if (res == INF) puts("No solution.");
    else
    {
        for (int i = 0; i < cnt; i ++ ) cout << path[i] << ' ';
        cout << endl;
    }
    return 0;
}