forked from zhuli19901106/poj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
POJ1287(AC).cpp
86 lines (75 loc) · 1.17 KB
/
POJ1287(AC).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
using namespace std;
typedef struct st{
int a;
int b;
int c;
}st;
bool comparator(const st &x, const st &y)
{
return x.c < y.c;
}
const int MAXP = 55;
int p, r;
int f[MAXP][MAXP];
int dj[MAXP];
int res;
vector<st> v;
int find_root(int x)
{
int k, r;
r = x;
while(dj[r] != r){
r = dj[r];
}
k = x;
while(x != r){
x = dj[x];
dj[k] = r;
k = x;
}
return r;
}
int main()
{
int ra, rb;
st vst;
int i, cc;
while(scanf("%d", &p) == 1 && p){
scanf("%d", &r);
v.clear();
memset(dj, 0, MAXP * sizeof(int));
memset(f, 0, MAXP * MAXP * sizeof(int));
for(i = 0; i < r; ++i){
scanf("%d%d%d", &vst.a, &vst.b, &vst.c);
v.push_back(vst);
}
sort(v.begin(), v.end(), comparator);
for(i = 0; i < p; ++i){
dj[i] = i;
}
res = 0;
cc = 0;
for(i = 0; i < (int)v.size(); ++i){
if(cc >= p - 1){
break;
}else{
ra = find_root(v[i].a);
rb = find_root(v[i].b);
if(ra != rb){
dj[ra] = rb;
find_root(v[i].a);
find_root(v[i].b);
res += v[i].c;
}
}
}
printf("%d\n", res);
}
return 0;
}