201812-4 | |
试题名称: | 数据中心 |
时间限制: | 1.0s |
内存限制: | 512.0MB |
问题描述: | 样例输入 4 样例输出 4 样例说明 下图是样例说明。 |
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int MAXN = 500010;
typedef struct Node {
int u, v, w;
Node(int a, int b, int c) :u(a), v(b), w(c) {}
}node;
vector<node>G;
vector<int>father(MAXN);
int find(int x) {
if (x == father[x]) return x;
else {
int F = find(father[x]);
father[x] = F;
return F;
}
}
bool cmp(node a, node b) {
if (a.w != b.w) return a.w < b.w;
return true;
}
int main() {
int n, m, root;
int a, b, c;
while (cin >> n >> m >> root) {
G.clear();
for (int i = 1; i <= n; i++) father[i] = i;
for (int i = 0; i < m; i++) {
cin >> a >> b >> c;
G.push_back(Node(a, b, c));
}
sort(G.begin(), G.end(), cmp);
int cnt = 0, index = 0, ans = 0;
while (cnt < n - 1) {
if (find(G[index].u) != find(G[index].v)) {
father[find(G[index].u)] = find(G[index].v);
ans = G[index].w, cnt++;
}
index++;
}
cout << ans << endl;
}
return 0;
}
解题思路:最小生成树(克鲁斯卡尔)加并查集(路径压缩)