题解
题意:n个集合,在满足集合内各个点的距离为0的条件下,求集合间的最短路
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int INF = 0x3f3f3f3f;
int c[N];
int n, m, K;
int fa[N];
int d[505][505];
int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int main() {
ios::sync_with_stdio(0);
cin >> n >> m >> K;
for (int i = 1; i <= n; ++i) {
fa[i] = i;
}
for (int i = 1; i <= K; ++i) {
cin >> c[i];
c[i] += c[i - 1];
}
for (int i = 1; i <= K; ++i) {
for (int j = 1; j <= K; ++j) {
d[i][j] = (i == j ? 0 : INF);
}
}
for (int i = 1, u, v, w; i <= m; ++i) {
cin >> u >> v >> w;
int a = lower_bound(c + 1, c + K + 1, u) - c;
int b = lower_bound(c + 1, c + 1 + K, v) - c;
d[a][b] = d[b][a] = min(d[a][b], w);
if (!w) {
//将集合最后一个元素作为father
int fx = find(u), fy = find(v);
if (fy > fx) fa[fx] = fy;
else fa[fy] = fx;
}
}
for (int i = 1; i <= K; ++i) {
int father = find(c[i]); //存在不同类型的集合之间的最短路为0 所以需要find()到底
for (int j = c[i - 1] + 1; j < c[i]; ++j) {
if (father != fa[find(j)]) {
return cout << "No" << endl, 0;
}
}
}
for (int k = 1; k <= K; ++k) {
for (int i = 1; i <= K; ++i) {
for (int j = 1; j <= K; ++j) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
cout << "Yes" << endl;
for (int i = 1; i <= K; ++i) {
for (int j = 1; j <= K; ++j) {
if (d[i][j] == INF) d[i][j] = -1;
cout << d[i][j] << ' ';
}
cout << endl;
}
return 0;
}