Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<cstdio>
- #include<vector>
- #include<algorithm>
- using namespace std;
- #define si(n) scanf("%d",&n)
- #define f first
- #define s second
- #define mp(a,b) make_pair(a,b)
- #define MAX 10004
- vector<int>graph[MAX];
- vector<pair<int,pair<int,int> > >edge;
- int n,m,parent[MAX],rnk[MAX];
- void make_set (int v) {
- parent[v] = v;
- rnk[v] = 0;
- }
- int find_set (int v) {
- if (v == parent[v])
- return v;
- return parent[v] = find_set (parent[v]);
- }
- void union_sets (int a, int b) {
- a = find_set (a);
- b = find_set (b);
- if (a != b) {
- if (rnk[a] < rnk[b])
- swap (a, b);
- parent[b] = a;
- if (rnk[a] == rnk[b])
- ++rnk[a];
- }
- }
- int main()
- {
- int i,j;
- si(n);si(m);
- for(i=0;i<m;i++){
- int u,v,w;
- si(u);si(v);si(w);
- graph[u].push_back(v);
- graph[v].push_back(u);
- edge.push_back(mp(w,mp(u,v)));
- }
- sort(edge.begin(),edge.end());
- long long MST=0;
- for(i=1;i<=n;i++)
- make_set(i);
- for(i=0;i<m;i++){
- int u=edge[i].s.f,v=edge[i].s.s,w=edge[i].f;
- if(find_set(u)==find_set(v))
- continue;
- MST+=w;
- union_sets(u,v);
- }
- cout<<MST<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement