题目大意:给你N条边,看能否形成最小生成树,如果存在,输出值,不存在,另外输出
解题思路:模版题
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
const int MAXNODE = 1010;
const int MAXEDGE = 1000010;
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, cas = 1;
int f[MAXNODE];
Type maxcost[MAXNODE][MAXNODE];
vector<Edge> G[MAXNODE];
map<string,int> Map;
//初始化并查集和最小生成树的边
void init() {
Map.clear();
n = 0;
cin >> m;
string a, b;
int val;
for (int i = 0; i < m; i++) {
cin >> a >> b >> val;
if (!Map[a]) Map[a] = ++n;
if (!Map[b]) Map[b] = ++n;
E[i] = Edge(Map[a], Map[b], val);
}
for (int i = 1; i <= n; i++) {
f[i] = i;
G[i].clear();
}
}
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)
cout << "Case " << cas++ << ": Impossible" << endl;
else
cout << "Case " << cas++ << ": " << Sum << endl;
}
int main() {
int test;
cin >> test;
while (test--) {
init();
solve();
}
return 0;
}