Advertisement
Guest User

Untitled

a guest
Jan 27th, 2015
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #include<cstdio>
  2. #include<algorithm>
  3. using namespace std;
  4. void MakeSet(int);
  5. int Find(int);
  6. bool Same_Component(int,int);
  7. void Union(int, int);
  8. int Components(int);
  9. struct Path {
  10. int origin;
  11. int destiny;
  12. int cost;
  13. }path[20005];
  14. bool operator < (Path a, Path b) {
  15. return a.cost < b.cost;
  16. }
  17. int root[1005];
  18. int rank[1005];
  19. int main() {
  20. int barns,connections;
  21. int mst = 0;
  22. scanf("%d %d",&barns,&connections);
  23. MakeSet(barns);
  24. for(int i=0;i<connections;i++){
  25. scanf("%d %d %d",&path[i].origin,&path[i].destiny,&path[i].cost);
  26. Union(path[i].origin,path[i].destiny);
  27. }
  28. if(Components(barns) != 1) printf("-1\n");
  29. else {
  30. sort(path,path+connections);
  31. MakeSet(barns+1);
  32. for(int i=connections-1;i>=0;i--) {
  33. if(!Same_Component(path[i].origin,path[i].destiny))
  34. mst += path[i].cost;
  35. Union(path[i].origin,path[i].destiny);
  36. }
  37. printf("%d\n",mst);
  38. }
  39. return 0;
  40. }
  41. void MakeSet(int n) {
  42. for(int i=0;i<n;i++) {
  43. root[i] = i;
  44. rank[i] = 0;
  45. }
  46. }
  47. int Find(int x) {
  48. if(x != root[x]) return root[x] = Find(root[x]);
  49. return x;
  50. }
  51. bool Same_Component(int x, int y) {
  52. if(Find(x) == Find(y)) return true;
  53. return false;
  54. }
  55. void Union(int x, int y) {
  56. int xroot = Find(x);
  57. int yroot = Find(y);
  58. if(rank[xroot] > rank[yroot]) root[yroot] = xroot;
  59. else {
  60. root[xroot] = yroot;
  61. if(rank[xroot] == rank[yroot]) rank[yroot]++;
  62. }
  63. }
  64. int Components(int n) {
  65. int nComponents = 0;
  66. for(int i=0;i<n;i++) {
  67. if(Find(i) == i) {
  68. root[nComponents] = i;
  69. nComponents++;
  70. }
  71. }
  72. return nComponents;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement