CF295B Greg and Graph 题解 floyd性质题

题目链接:https://codeforces.com/problemset/problem/295/B

题目描述可参见 洛谷

解题思路完全来自 aiiYuu巨佬的博客

一道很好地利用了 floyd 算法性质的题目。

floyd算法

示例程序:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 505;
long long ans[maxn];
int n, x[maxn], a[maxn][maxn], f[maxn][maxn], d[maxn][maxn];
bool vis[maxn];

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            scanf("%d", &a[i][j]);
    for (int i = 1; i <= n; i++) scanf("%d", x+i);
    for (int t = n; t >= 1; t--) {
        int k = x[t];
        vis[k] = true;
        for (int i = 1; i <= n; i++) {
            if (!f[i][k] || f[i][k] > a[i][k])
                f[i][k] = a[i][k];
            if (!f[k][i] || f[k][i] > a[k][i])
                f[k][i] = a[k][i];
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == j) continue;
                if (!f[i][j] || f[i][j] > f[i][k] + f[k][j])
                    f[i][j] = f[i][k] + f[k][j];
            }
        }
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                if (vis[i] && vis[j])
                    ans[t] += f[i][j];
    }
    for (int i = 1; i <= n; i++)
        printf("%lld ", ans[i]);
    return 0;
}
posted @ 2024-01-04 16:09  quanjun  阅读(12)  评论(0编辑  收藏  举报