Description

[HDU1599]find the mincost route

Solution

恶补图论,最小环问题的板子题
\(floyd\)来判最小环,复杂度\(O(n^3)\)
枚举\(k\)\(1\)\(n\)
最小环的\(i\)\(1\)\(k-1\)\(j\)\(1\)\(i-1\)
\(ans=min(ans,f[i][j]+a[i][k]+a[k][j])\)
同时维护最短路数组的\(i\)\(1\)\(n\)\(j\)\(1\)\(n\)

Code

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
#define ll long long
#define INF 0x7ffffff
#define MAXN 110
ll n, m, x, y, z, ans;
ll a[MAXN][MAXN], f[MAXN][MAXN];
inline ll read() {
    ll s = 0, w = 1;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
    for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
    return s * w;
}
int main() {
    while (scanf("%lld%lld", &n, &m) == 2) {
        for (register ll i = 1; i <= n; i++)
            for (register ll j = 1; j <= n; j++)
                a[i][j] = f[i][j] = INF;
        for (register ll i = 1; i <= m; i++) {
            x = read(), y = read(), z = read();
            a[x][y] = a[y][x] = min(a[x][y], z);
            f[x][y] = f[y][x] = min(f[x][y], z);
        }
        ans = INF;
        for (register ll k = 1; k <= n; k++) {
            for (register ll i = 1; i < k; i++)
                for (register ll j = i + 1; j < k; j++)
                    ans = min(ans, f[i][j] + a[i][k] + a[k][j]);
            for (register ll i = 1; i <= n; i++)
                for (register ll j = 1; j <= n; j++)
                    f[i][j] = min(f[i][j], f[i][k] + f[k][j]);
        }
        if (ans == INF)
            printf("It's impossible.\n");
        else
            printf("%lld\n", ans);
    }
    return 0;
}
12-30 15:48