码迷,mamicode.com
首页 > 其他好文 > 详细

[HDU1599]find the mincost route

时间:2019-11-06 21:16:51      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:while   out   min   print   line   esc   scanf   ++   std   

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;
}

[HDU1599]find the mincost route

标签:while   out   min   print   line   esc   scanf   ++   std   

原文地址:https://www.cnblogs.com/Agakiss/p/11808713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!