Advertisement
Guest User

Untitled

a guest
Aug 25th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<vector>
  3. #include<algorithm>
  4. #include<queue>
  5. using namespace std;
  6. struct edge
  7. {
  8. int a,b,we;
  9. edge(){}
  10. edge(int u,int v,int weight)
  11. {
  12. a=u;b=v;we=weight;
  13. }
  14. bool operator >(const edge &a)const
  15. {
  16. return we>a.we;
  17. }
  18. bool operator <(const edge &q)const
  19. {
  20. if(we==q.we) return a<q.a;
  21. return we<q.we;
  22. }
  23. };
  24. vector<edge> ed,mst;
  25. int p[1010];
  26. int parent(int i)
  27. {
  28. if(p[i]==i) return i;
  29. p[i]=parent(p[i]);
  30. return p[i];
  31. }
  32. main()
  33. {
  34. int i,j,a,b,c,n,m;
  35. scanf("%d %d",&n,&m);
  36. for(i=0;i<m;i++)
  37. {
  38. scanf("%d %d %d",&a,&b,&c);
  39. ed.push_back(edge(a,b,c));
  40. }
  41. sort(ed.begin(),ed.end());
  42. for(i=0;i<n;i++)
  43. {
  44. p[i]=i;
  45. }
  46. //printf("%d\n",ed.size());
  47. int cost=0;
  48. for(i=0;i<ed.size();i++)
  49. {
  50. edge u=ed[i];
  51. //printf("%d %d %d\n",u.a,u.b,u.we);
  52. if(parent(u.a)!=parent(u.b))
  53. {
  54. p[p[b]]=p[a];
  55. mst.push_back(u);cost+=u.we;
  56. //printf("sum=%d\n",cost);
  57. }
  58. }
  59. //printf("%d\n",mst.size());
  60. printf("%d\n",cost);
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement