-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSETUNION.cpp
More file actions
78 lines (76 loc) · 1.24 KB
/
SETUNION.cpp
File metadata and controls
78 lines (76 loc) · 1.24 KB
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
// Author : Manish Sharma
//
// Set Union
// SPOJ Problem : Dark roads
// http://www.spoj.com/problems/ULM09/
#include<bits/stdc++.h>
#define s(a) scanf("%d",&a)
#define ss(a) scanf("%s",&a)
using namespace std;
typedef long long int ll;
typedef struct edge{
int x,y,w;
} edge;
bool operator< (const edge &l, const edge &r)
{
return (l.w < r.w);
}
edge inp[200005];
short visited[200005];
int p[200005],rank[200005];
int findset(int node)
{
if(p[node]!=node)
p[node]=findset(p[node]);
return p[node];
}
inline bool mergeset(int x,int y)
{
int px = findset(x);
int py = findset(y);
if(px == py)return false;
if(rank[px]<rank[py])
p[px] = py;
else
p[py] = px;
if(rank[px] == rank[py])
rank[px] = rank[px] + 1;
return true;
}
int main()
{
int n,i,m,x,y,w;
int res,total,count;
while(1)
{
s(n);
s(m);
res = 0; total = 0; count=0;
if(!(n && m))
return 0;
for(i=0;i<m;i++)
{
scanf("%d %d %d",&(inp[i].x),&(inp[i].y),&(inp[i].w));
total += inp[i].w;
}
sort(inp,inp+m);
for(i=0;i<n;i++)
{
p[i]=i;
rank[i]=0;
}
for(i=0;i<m;i++)
{
if(count == n-1)
break;
bool temp = mergeset(inp[i].x,inp[i].y);
if(temp)
{
res += inp[i].w;
count++;
}
}
printf("%d\n",total-res);
}
return 0;
}