JZ junior OJ 1342. [2009 Nanhai junior] cowtract

Title Description

  Bessie hired John came to the farm to help them build internet network. Farm N (2 <= N <= 1,000) cow, No. 1..N. Has been previously surveyed, John, found M (1 <= M <= 20,000) possible connection strip line, a line connecting two of a barn. Each line may have a construction cost C (1 <= C <= 100,000). John of course, want to spend as little money, even Bessie deduction of wages.

  Bessie found this point, very angry, John decided to make trouble. She wanted to select some lines form networks, but the costs are as large as possible. Of course, the network must be able to work properly, that is, any communication between the two are mutually bullpen, and can not have a ring on your network, or else John will be very easy to find.

 Calculate the potential cost up to set up such a network.
 

Entry

The first line: two integers NM

M following lines: line 3 each integers A, B, C. Represents a possible connection to the line A, B two cowshed, cost C.

Export

Only one line, an integer that is the most costly expense. If the connection is not possible through all cowshed, outputs -1.
 

Sample input

 

Sample Output

 
 

Data range limit

 
 

prompt

 
















Entry

5 8

1 2 3

1 3 7

2 3 10       

2 4 4

2 5 8

3 4 6

3 5 2

4 5 17

17 + 8 + 10 + 7 = 42

Export

42
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,m,ans,ans1,fa[20001],flag;
 4 struct cow{
 5     int father,son,cost;
 6 }tree[20001];
 7 bool cmp(cow x,cow y)
 8 {
 9     return x.cost>y.cost;
10 }
11 int find(int x)
12 {
13     if(fa[x]==x)
14     return x;
15     else
16     return fa[x]=find(fa[x]);
17 }
18 void add(int x,int y)
19 {
20     fa[fa[x]]=fa[y];
21 }
22 int main()
23 {
24     cin>>n>>m;
25     for(int i=1;i<=n;i++)
26     fa[i]=i;
27     for(int i=1;i<=m;i++)
28     {
29         cin>>tree[i].father>>tree[i].son>>tree[i].cost;
30     }
31     sort(tree+1,tree+1+m,cmp);
32     for(int i=1;i<=m;i++)
33     {
34         if(find(tree[i].father)!=find(tree[i].son))
35         {   
36             ans1++;
37             add(tree[i].father,tree[i].son);
38             ans+=tree[i].cost;
39         }    
40     }
41     if (n == years1 1 )
 42      {
 43          cout << years;
44          return  0 ;
45      }
 46      else 
47      cout << - 1 ;
48      return  0 ;
49 }

Guess you like

Origin www.cnblogs.com/anbujingying/p/11306737.html
Recommended