SumMin
[link](CSUSTOJ | SumMin)
题意
一个图,有 n n n 个点,任意两点直接有两条相互指向的有向边,且每条边都有一个权值 w w w ,接下来 n n n次操作,每次删除一个点 u u u并删除所有从 u u u出发的边,求剩下的所有点中任意两点之间的最短路的和。
题解
因为删除的点是从前往后删除的。floyd的第k层循环求的是只用前k个点且 u − > v u->v u−>v的最短路是多少,所以我们倒着跑一遍floyd就可以了。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#include <deque>
#include <sstream>
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 510, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
LL d[N][N];
int a[N];
bool ok[N];
int main() {
ios::sync_with_stdio(false), cin.tie(0);
cin >> n;
vector<LL> res;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
cin >> d[i][j];
for (int i = 1; i <= n; i ++ ) cin >> a[i];
for (int u = n; u; u -- ) {
LL sum = 0, k = a[u]; ok[k] = true;
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];
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
if (ok[i] && ok[j]) sum += d[i][j];
res.push_back(sum);
}
for (int i = res.size() - 1; i >= 0; i -- )
cout << res[i] << ' ';
cout << endl;
return 0;
}
本文介绍了一种解决图论问题的方法,通过Floyd算法的逆向应用,计算在逐步删除节点及其边后,剩余节点间最短路径之和。博客给出了详细题解、代码实现及应用场景,适合理解图算法动态调整的技巧。

被折叠的 条评论
为什么被折叠?



