题目大意:给你一个邻接矩阵,表示两点之间的花费,现在问,花费总和-最小生成树的值
如果最小生成树不存在,另外输出
解题思路:模版题
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXNODE = 110;
const int MAXEDGE = 50010;
typedef int Type;
struct Edge{
int u, v;
Type d;
Edge() {}
Edge(int u, int v, Type d): u(u), v(v), d(d) {}
}E[MAXEDGE];
int n, m, tot, sum, cas = 1;
int f[MAXNODE];
Type maxcost[MAXNODE][MAXNODE];
vector<Edge> G[MAXNODE];
//初始化并查集和最小生成树的边
void init() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
f[i] = i;
G[i].clear();
}
sum = m = 0;
int val;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
scanf("%d", &val);
if (val != 0) {
E[m++] = Edge(i, j, val);
sum += val;
}
}
}
int find(int x) {
return x == f[x] ? x : f[x] = find(f[x]);
}
bool cmp(const Edge &a, const Edge &b) {
return a.d < b.d;
}
//dfs找路径最大值,maxcost[i][j]维护的是树上的i到j点的路径上,最长的那条边的权值
void dfs(int s, int u, Type Max, int fa) {
maxcost[s][u] = max(maxcost[s][u], Max);
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].v;
if (v == fa) continue;
double tmp = max(Max, G[u][i].d);
dfs(s, v, tmp, u);
}
}
//Kruskal找到最小生成树,并将最小生成树记录下来,以便后面用来求两点之间的最长边
void solve() {
sort(E, E + m, cmp);
Type Sum = 0;
int num = 0;
for (int i = 0; i < m; i++) {
int fx = find(E[i].u);
int fy = find(E[i].v);
if (fx != fy) {
f[fx] = fy;
Sum += E[i].d;
G[E[i].u].push_back(E[i]);
swap(E[i].u, E[i].v);
G[E[i].u].push_back(E[i]);
num++;
}
}
if (num != n - 1)
printf("Case %d: %d\n", cas++ , -1);
else
printf("Case %d: %d\n", cas++, sum - Sum);
}
int main() {
int test;
scanf("%d", &test);
while (test--) {
init();
solve();
}
return 0;
}