-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minimum Spanning tree
136 lines (121 loc) · 2.33 KB
/
Minimum Spanning tree
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include<bits/stdc++.h>
using namespace std;
#define scn(n) scanf("%d",&n)
#define lscn(n) scanf("%lld",&n)
#define lpri(n) printf("%lld",n)
#define pri(n) printf("%d",n)
#define pln() printf("\n")
#define priln(n) printf("%d\n",n)
#define lpriln(n) printf("%lld\n",n)
#define fr(i,init,n) for(int i=init;i<n;i++)
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define gcd __gcd
#define inf INT_MAX
#define ninf INT_MIN
#define f(v,value) find(v.begin(),v.end(),value)
#define asc(a,n) sort(a,a+n)
#define desc(a,n,data_type) sort(a,a+n,greater<data_type>())
#define vasc(v) sort(v.begin(),v.end())
#define vdesc(v,data_type) sort(v.begin(),v.end(),greater<data_type>())
const int mod = 1e9 + 7;
const int N = 1e5 + 4;
int check(int val)
{
int k2=val;int t=0;int sum=0;
val=val-val%5;
while(k2>0)
{
k2=k2/5;
t++;
//cout<<"k2"<<k2;
}
t--;//cout<<t<<" ";
int k1=pow(5,t);
//cout<<k1;
while(k1>=5)
{
sum+=val/k1;
k1=k1/5;
//cout<<sum<<"@ "<<k1;
}
//cout<<val<<"sum"<<sum<<" ";
return sum;
}
int bi_search(int k)
{
int low=0;
int high=1e12;
int pos;
while(high>low)
{
int mid=(low+high)/2;
//cout<<"mid"<<mid<<" ";
if(check(mid)>=k)
{
pos=mid; //cout<<pos<<" ";
high=mid-1;
}
else
low=mid+1;
}
return pos;
}
struct edge
{
int a;
int b;
int w;
};
edge arr[100005];
int par[100005];
int find(int a)
{
if(par[a]==-1)
return a;
else
return par[a]=find(par[a]);
}
bool comp(edge a,edge b)
{
if(a.w<b.w)
return true;
else
return false;
}
void merger(int a, int b)
{
par[a]=b;
}
int main()
{
int n;
cin>>n;
int m;
cin>>m;
fr(i,0,n+1)
par[i]=-1;
fr(i,0,m)
{
cin>>arr[i].a>>arr[i].b>>arr[i].w;
}
sort(arr,arr+m,comp);
int sum=0;
fr(i,0,m)
{
int a1=find(arr[i].a);
int a2=find(arr[i].b);
//cout<<arr[i].a<<" "<<a1<<" b "<<arr[i].b<<" "<<a2<<endl;
if(a2!=a1)
{
sum+=arr[i].w;
//cout<<arr[i].a<<" "<<arr[i].b<<endl;
par[a1]=a2;
//cout<<arr[i].a<<" "<<par[arr[i].a]<<" "<<endl;
}
}//cout<<par[5]<<" ";
cout<<sum;
return 0;
}