1005. F.Snowy Roads
|
最小生成树
Kruskal 算法
主要参考算法导论
1. A <- 空集
2. for each vertex v ∈ V[G]
3. do Create-Set(v)
4. sort the edges of E by nondecreasing weight w
5. for each edge (u,v)∈E, in order bynondecreasing weight
6. do if Find-Set(u) != Find-Set(v)
7. then A <- A ∪ {(u,v)}
8. Union(u,v)
9. return A
总的算法时间也可以表述为O(E lg V)。
联系题目:
Description
There was a heavy snow in the town yesterday. Some roads in the town are covered with thick snow so that they are hard to pass. The Snow Cleaning Team wants to make the intersections in the town connect to each other, in other words, one can walk from any intersection to any others only by passing the roads without snow. And they want the length of the snowy roads they have to clean is as short as possible. Help them to find the minimum length of the roads they must clean.
Input
The first line is a positive integer T (0<T<=10), T test cases follow. For each of the test case, the first line will be three non-negative integers N (0<N<=100), the number of intersections in the town, M1 (0<=M1<=1000), the number of roads that are not covered with snow, and M2 (0<=M2<=1000), the number of roads covered with snow. The intersections are numbered from 0 to N-1. Then M1 lines follow, each of the lines contain two integers X, Y (0<=X, Y<N, X≠Y), it means that there is a road without snow between intersection X and Y. Then M2 lines follow, each of the lines contain three integers X, Y, Z (0<=X, Y<N, X≠Y, 0<Z<=1000), it means that there is a road with snow between intersection X and Y, and the team need time Z minutes to clean it. It is guaranteed that it is possible to clean some snowy roads to make all the intersections connected. And there is at most one road between two intersections.
Output
For each of the test cases output only one integer in one line, the minimum length of the snowy roads they have to clean.
Sample Input
3 3 0 3 0 1 4 1 2 5 2 0 6 4 3 3 2 1 0 1 2 3 3 1 1 0 3 3 0 2 2 4 3 3 3 1 1 2 2 3 0 3 7 0 2 8 0 1 9
Sample Output
9 0 7 |
#include <iostream>
#include <algorithm>
using namespace std;
struct Node{
int u;
int v;
int weight;
Node() {}
Node(int u,int v,int weight):u(u),v(v),weight(weight){}
};
bool cmp(Node a,Node b) {
return a.weight < b.weight;
}
Node nodes[2002];
int root[101];
int main() {
int T;
cin >> T;
while(T--) {
int N,M1,M2;
cin >> N >> M1 >> M2;
for(int i = 0;i < M1; i++) {
int x,y;
cin >> x >> y;
nodes[i].u = x;
nodes[i].v = y;
nodes[i].weight = 0;
}
for(int i = M1;i < M1 + M2;i ++) {
int x,y,z;
cin >> x >> y >> z;
nodes[i].u = x;
nodes[i].v = y;
nodes[i].weight = z;
}
for(int i = 0;i < N;i ++) {
root[i] = i;
}
sort(nodes,nodes + M1 +M2,cmp);
int length = 0;
for(int i = 0;i < M1 + M2;i ++) {
Node temp = nodes[i];
if(root[temp.u] != root[temp.v]) {
length += temp.weight;
int root_u = root[temp.u];
int root_v = root[temp.v];
for(int j = 0;j < N;j ++) {
if(root[j] == root_v) {
root[j] = root_u;
}
}
}
}
cout << length<<endl;
}
return 0;
}