Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<vector>
- #include<algorithm>
- #include<queue>
- using namespace std;
- struct edge
- {
- int a,b,we;
- edge(){}
- edge(int u,int v,int weight)
- {
- a=u;b=v;we=weight;
- }
- bool operator >(const edge &a)const
- {
- return we>a.we;
- }
- bool operator <(const edge &q)const
- {
- if(we==q.we) return a<q.a;
- return we<q.we;
- }
- };
- vector<edge> ed,mst;
- int p[1010];
- int parent(int i)
- {
- if(p[i]==i) return i;
- p[i]=parent(p[i]);
- return p[i];
- }
- main()
- {
- int i,j,a,b,c,n,m;
- scanf("%d %d",&n,&m);
- for(i=0;i<m;i++)
- {
- scanf("%d %d %d",&a,&b,&c);
- ed.push_back(edge(a,b,c));
- }
- sort(ed.begin(),ed.end());
- for(i=0;i<n;i++)
- {
- p[i]=i;
- }
- //printf("%d\n",ed.size());
- int cost=0;
- for(i=0;i<ed.size();i++)
- {
- edge u=ed[i];
- //printf("%d %d %d\n",u.a,u.b,u.we);
- if(parent(u.a)!=parent(u.b))
- {
- p[p[b]]=p[a];
- mst.push_back(u);cost+=u.we;
- //printf("sum=%d\n",cost);
- }
- }
- //printf("%d\n",mst.size());
- printf("%d\n",cost);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement