Advertisement
gilzean

Untitled

May 22nd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include <fstream>
  2. #include <cmath>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <iomanip>
  6.  
  7. using namespace std;
  8. ifstream f("desen.in");
  9. ofstream g("desen.out");
  10.  
  11. class Punct {
  12. public:
  13. int x, y;
  14. double dist(Punct P) {
  15. return sqrt( (double) (x - P.x) * (x - P.x) + (y - P.y) * (y - P.y) );
  16. }
  17. friend istream& operator >> (istream& is, Punct &P) {
  18. is >> P.x >> P.y;
  19. return is;
  20. }
  21. };
  22.  
  23. int N, i, j;
  24. Punct Puncte[1001];
  25. int uf[1001], H[1001];
  26. double sol;
  27.  
  28. class Muchie {
  29. public:
  30. int x, y;
  31. double cost;
  32. Muchie(int p1, int p2) {
  33. x = p1;
  34. y = p2;
  35. cost = Puncte[x].dist(Puncte[y]);
  36. }
  37. bool operator < (Muchie M) const {
  38. return cost < M.cost;
  39. }
  40. };
  41.  
  42. int Find(int x) {
  43. if (x == uf[x]) {
  44. return x;
  45. }
  46. int root = Find(uf[x]);
  47. uf[x] = root;
  48. return root;
  49. }
  50.  
  51. void Union (int x, int y) {
  52. x = Find(x);
  53. y = Find(y);
  54. if (H[x] < H[y]) {
  55. uf[x] = y;
  56. }
  57. else if (H[x] > H[y]) {
  58. uf[y] = x;
  59. }
  60. else {
  61. uf[x] = y;
  62. H[y] ++;
  63. }
  64. }
  65.  
  66. double Kruskal (int N, vector <Muchie> &M, vector <Muchie> &B) {
  67.  
  68. double res = 0;
  69. int i;
  70. for (i = 1; i <= N; ++i) {
  71. uf[i] = i;
  72. H[i] = 1;
  73. }
  74. sort(M.begin(), M.end());
  75. int k = 0;
  76. for (auto v : M) {
  77. if (Find(v.x) != Find(v.y)) {
  78. Union(v.x, v.y);
  79. B.push_back(v);
  80. res += v.cost;
  81. ++k;
  82. }
  83. if (k == N - 1)
  84. return res;
  85. }
  86. return -1;
  87. }
  88. vector <Muchie> A, B;
  89.  
  90. int main() {
  91. f >> N;
  92. for (i = 1; i <= N; ++i)
  93. f >> Puncte[i];
  94. g << fixed << setprecision(6) << 0.0 << '\n';
  95. for (i = 2; i <= N; ++i) {
  96. for (j = 1; j < i; ++j)
  97. A.push_back( Muchie(i, j) );
  98. sol = Kruskal (i, A, B);
  99. A = B;
  100. B.clear();
  101. g << fixed << setprecision(6) << sol << '\n';
  102. }
  103. return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement