Advertisement
Guest User

Untitled

a guest
May 29th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int rooms[55][55];
  5. int parent[55],n;
  6. #define edges pair <int,int>
  7. vector < pair <int, edges> > abid;
  8. bool check;
  9.  
  10. int get_parent(int x)
  11. {
  12. if(x!=parent[x])
  13. parent[x]=get_parent(parent[x]);
  14.  
  15. return parent[x];
  16. }
  17.  
  18. int kruskal()
  19. {
  20. int total=0;
  21. int pu,pv,i;
  22. sort(abid.begin(),abid.end());
  23.  
  24. for(i=0;i<abid.size();i++)
  25. {
  26. pu=get_parent(abid[i].second.first);
  27. pv=get_parent(abid[i].second.second);
  28.  
  29. if(pu!=pv)
  30. {
  31. total+=abid[i].first;
  32. parent[pu]=parent[pv];
  33. }
  34.  
  35. }
  36. return total;
  37. }
  38.  
  39. int main()
  40. {
  41. int T,cs=1;
  42. scanf("%d",&T);
  43. while(T--)
  44. {
  45. int min_wire=0,donation=0,total_wire=0,i,j;
  46. scanf("%d",&n);
  47. total_wire=0;
  48. for(i=1;i<=n;i++)
  49. for(j=1;j<=n;j++)
  50. {
  51. scanf("%d",&rooms[i][j]);
  52. if(j!=i && rooms[i][j]!=0)
  53. {
  54. abid.push_back( pair<int,edges> (rooms[i][j],edges(i,j)));
  55. }
  56. total_wire+=rooms[i][j];
  57. }
  58.  
  59. for(i=1;i<=n;i++)
  60. parent[i]=i;
  61.  
  62. min_wire=kruskal();
  63. donation=total_wire-min_wire;
  64. check=1;
  65. for(i=1;i<n;i++)
  66. if(parent[i]!=parent[i+1])
  67. {
  68. printf("Case %d: -1\n",cs++);
  69. check=0;
  70. break;
  71. }
  72.  
  73. if(check)
  74. printf("Case %d: %d\n",cs++,donation);
  75. abid.clear();
  76. }
  77.  
  78. return 0;
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement