ECNUOJ 2573 Hub Connection plan

Hub Connection plan

Time Limit:1000MS Memory Limit:65536KB
Total Submit:743 Accepted:180

Description

Partychen is working as system administrator and is planning to establish a new network in his company. There will be N hubs in the company, they can be connected to each other using cables. Since each worker of the company must have access to the whole network, each hub must be accessible by cables from any other hub (with possibly some intermediate hubs).
Since cables of different types are available and shorter ones are cheaper, it is necessary to make such a plan of hub connection, that the cost is minimal. partychen will provide you all necessary information about possible hub connections. You are to help partychen to find the way to connect hubs so that all above conditions are satisfied.

Input

The first line of the input contains two integer numbers: N - the number of hubs in the network (2 <= N <= 1000) and M - the number of possible hub connections (1 <= M <= 15000). All hubs are numbered from 1 to N. The following M lines contain information about possible connections - the numbers of two hubs, which can be connected and the cable cost required to connect them. cost is a positive integer number that does not exceed 106. There will always be at least one way to connect all hubs.

Output

Output the minimize cost of your hub connection plan.

Sample Input

4 6
1 2 1
1 3 1
1 4 2
2 3 1
3 4 1
2 4 1

Sample Output

3
Hint
We can build net from 1 to 2 to 3 to 4,then we get the cost is 3.Of course you can get 3 by other way.

Source

解题:最小生成树模板

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 20010;
 4 struct arc{
 5     int u,v,w;
 6     bool operator<(const arc &t)const{
 7         return w < t.w;
 8     }
 9 }e[maxn];
10 int uf[maxn],n,m;
11 int Find(int x){
12     if(x != uf[x]) uf[x] = Find(uf[x]);
13     return uf[x];
14 }
15 int main(){
16     while(~scanf("%d %d",&n,&m)){
17         for(int i = 0; i < m; ++i)
18             scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
19         sort(e,e+m);
20         int ret = 0;
21         for(int i = 0; i <= n; ++i) uf[i] = i;
22         for(int i = 0; i < m; ++i){
23             int x = Find(e[i].u);
24             int y = Find(e[i].v);
25             if(x == y) continue;
26             ret += e[i].w;
27             uf[x] = y;
28         }
29         printf("%d
",ret);
30     }
31     return 0;
32 }
View Code
原文地址:https://www.cnblogs.com/crackpotisback/p/4628340.html