POJ 1251 Jungle Roads minimal spanning tree
The question is to give your graph and then find the value of the minimum spanning tree. Note the input.
Idea: kruskal water stops using the bare minimum spanning tree. I did not write the minimum spanning tree for a long time. I thought about it carefully and wrote it out.
Code:
- # Include
- # Include
- # Include
- # Include
- # Include
- Using namespace std;
-
- # Define CLR (arr, val) memset (arr, val, sizeof (arr ))
- Const int N = 32;
- Vector Vv [N];
- Int numedge, father [N];
- Struct edge {
- Int leftp, rightp, value;
- } Ee [1, 1000];
- Bool cmp (edge a, edge B ){
- Return a. value <B. value;
- }
- Int find (int x ){
- If (x = father [x])
- Return father [x];
- Return find (father [x]);
- }
- Bool union_set (int lp, int rp ){
- Int sequence = find (lp );
- Int frp = find (rp );
- If (records = frp ){
- Return false;
- }
- Else {
- Father [frp] = frp;
- Return true;
- }
- }
- Int kruskal (){
- Int sum = 0;
- For (int I = 0; I <numedge; ++ I ){
- Int lp = ee [I]. leftp;
- Int rp = ee [I]. rightp;
- If (union_set (lp, rp ))
- Sum + = ee [I]. value;
- }
- Return sum;
- }
- Int main (){
- // Freopen(1.txt, r, stdin );
- Int n;
- While (scanf (% d, & n ){
- Char ch;
- Int num, x;
- Numedge = 0;
- For (int I = 1; I <n; ++ I ){
- Cin> ch;
- Scanf (% d, & num );
- While (num --){
- Cin> ch;
- Scanf (% d, & x );
- Int y = (int) (ch-'A' + 1 );
- Ee [numedge]. leftp = I;
- Ee [numedge]. rightp = y;
- Ee [numedge]. value = x;
- Numedge ++;
- }
- }
- Sort (ee, ee + numedge, cmp );
- For (int I = 1; I <N; ++ I)
- Father [I] = I;
- Int ans = kruskal ();
- Printf (% d, ans );
- }
- Return 0;
- }