fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. struct eg
  8. {
  9. int f, t, w;
  10. friend bool operator < (const eg& a, const eg& b);
  11. };
  12.  
  13. bool operator < (const eg& a, const eg& b)
  14. {
  15. return a.w < b.w;
  16. }
  17.  
  18. int f(int n, const vector<int>& p)
  19. {
  20. if (p[n] == n)
  21. return n;
  22. else
  23. return f(p[n], p);
  24. }
  25.  
  26. void g(int a, int b, vector<int>& p)
  27. {
  28. if (rand()%2)
  29. p[a] = b;
  30. else
  31. p[b] = a;
  32. }
  33.  
  34. int main()
  35. {
  36. int n, m;
  37. cin >> n >> m;
  38.  
  39. vector<eg> e;
  40.  
  41. for (int i = 0; i < m; i++)
  42. {
  43. eg t;
  44. cin >> t.f >> t.t >> t.w;
  45. t.f--; t.t--;
  46. e.push_back(t);
  47. }
  48. sort(e.begin(), e.end());
  49. vector<int> p(n);
  50. for (int i = 0; i < n; i++)
  51. p[i] = i;
  52.  
  53. int se = INT_MAX, sum = 0, cnt = 0;
  54.  
  55. for (int i = 0; i < e.size(); i++)
  56. {
  57. int a = f(e[i].f, p), b = f(e[i].t, p);
  58. if (a == b)
  59. se = min(i, se);
  60. else
  61. {
  62. g(a, b, p);
  63. sum += e[i].w;
  64. cnt++;
  65. }
  66. }
  67.  
  68. if (cnt != n-1)
  69. {
  70. cout << "Cost: -1" << endl;
  71. cout << "Cost: -1" << endl;
  72. return 0;
  73. }
  74.  
  75. cout << "Cost: " << sum << endl;
  76.  
  77. if (se == INT_MAX)
  78. {
  79. cout << "Cost: -1" << endl;
  80. return 0;
  81. }
  82.  
  83. sum = e[se].w; cnt = 1;
  84. for (int i = 0; i < n; i++)
  85. p[i] = i;
  86. g(e[se].f, e[se].t, p);
  87.  
  88. for (int i = 0; i < e.size(); i++)
  89. {
  90. int a = f(e[i].f, p), b = f(e[i].t, p);
  91. if (a != b)
  92. {
  93. g(a, b, p);
  94. sum += e[i].w;
  95. cnt++;
  96. }
  97. }
  98.  
  99. if (cnt == n-1)
  100. cout << "Cost: " << sum;
  101. else
  102. cout << "Cost: -1";
  103.  
  104. return 0;
  105. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:53:11: error: 'INT_MAX' was not declared in this scope
  int se = INT_MAX, sum = 0, cnt = 0;
           ^
prog.cpp:63:4: error: 'sum' was not declared in this scope
    sum += e[i].w;
    ^
prog.cpp:64:4: error: 'cnt' was not declared in this scope
    cnt++;
    ^
prog.cpp:68:6: error: 'cnt' was not declared in this scope
  if (cnt != n-1)
      ^
prog.cpp:75:22: error: 'sum' was not declared in this scope
  cout << "Cost: " << sum << endl;
                      ^
prog.cpp:83:17: error: 'cnt' was not declared in this scope
  sum = e[se].w; cnt = 1;
                 ^
stdout
Standard output is empty