Source code for submission s908

Go to diff to previous submission

spider.cpp

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. struct edge {
  7. int u, v, l;
  8. bool operator<(const edge & rhs) const
  9. { return l < rhs.l; }
  10. };
  11.  
  12. vector<int> UF;
  13. vector<int> CS;
  14.  
  15. int find_set(int n) {
  16. if (n != UF[n])
  17. UF[n] = find_set(UF[n]);
  18. return UF[n];
  19. }
  20. bool connected(int u, int v)
  21. {
  22. return (find_set(u) == find_set(v));
  23. }
  24. int connect(int u, int v)
  25. {
  26. int uroot = find_set(u);
  27. int vroot = find_set(v);
  28. UF[uroot] = UF[vroot];
  29. CS[uroot] = CS[vroot] = CS[uroot] + CS[vroot];
  30. return CS[uroot];
  31. }
  32.  
  33. int main()
  34. {
  35. ios_base::sync_with_stdio(false);
  36. int N, M;
  37. while (cin >> N) {
  38. cin >> M;
  39. vector<edge> E (M);
  40. UF = vector<int> (N+1);
  41. CS = vector<int> (N+1);
  42. long netl = 0;
  43.  
  44. // UF
  45. for (int i = 0; i <= N; ++i) {
  46. UF[i] = i;
  47. CS[i] = 1;
  48. }
  49.  
  50. // load and sort
  51. for (int i = 0; i < M; ++i) {
  52. edge e;
  53. cin >> e.u >> e.v >> e.l;
  54. E[i] = e;
  55. }
  56. sort (E.begin(), E.end());
  57.  
  58. // connect longest
  59. edge longest = E.back();
  60. netl -= longest.l;
  61. connect(longest.u, longest.v);
  62. E.pop_back(); --M;
  63.  
  64. bool all = false; int ei = 0;
  65. while (ei < M && !all) {
  66. edge e = E[ei];
  67. if (!connected(e.u, e.v)) {
  68. if (connect(e.u, e.v) == N)
  69. all = true;
  70. netl += e.l;
  71. }
  72. ++ei;
  73. }
  74.  
  75. if (all) cout << netl << '\n';
  76. else cout << "disconnected\n";
  77. }
  78. return 0;
  79. }
  80.  

Diff to submission s811

spider.cpp

--- c4.s811.cteam012.spider.cpp.0.spider.cpp
+++ c4.s908.cteam012.spider.cpp.0.spider.cpp
@@ -22,8 +22,11 @@
         return (find_set(u) == find_set(v));
 }
-void connect(int u, int v)
+int connect(int u, int v)
 {
-        UF[u] = UF[v];
-        CS[u] = CS[v] = CS[u] + CS[v];
+        int uroot = find_set(u);
+        int vroot = find_set(v);
+        UF[uroot] = UF[vroot];
+        CS[uroot] = CS[vroot] = CS[uroot] + CS[vroot];
+        return CS[uroot];
 }
 
@@ -63,8 +66,7 @@
                         edge e = E[ei];
                         if (!connected(e.u, e.v)) {
-                                connect(e.u, e.v);
-                                netl += e.l;
-                                if (CS[e.u] == N)
+                                if (connect(e.u, e.v) == N)
                                         all = true;
+                                netl += e.l;
                         }
                         ++ei;