Advertisement
Guest User

Untitled

a guest
Jul 21st, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int INF = 1e9 + 7;
  6. const int MAXN = 507;
  7. const int MAXM = MAXN * MAXN;
  8.  
  9. struct Edge {
  10. int u, v, c;
  11. };
  12.  
  13. int n, m;
  14. Edge e[MAXM];
  15.  
  16. bool comp(Edge a, Edge b) {
  17. return a.c < b.c;
  18. }
  19.  
  20. int cnt[MAXN], par[MAXN];
  21.  
  22. int root(int u) {
  23. if (par[u] == u) return u;
  24. else return par[u] = root(par[u]);
  25. }
  26.  
  27. bool merge(int u, int v) {
  28. u = root(u);
  29. v = root(v);
  30. if (u == v) return 0;
  31.  
  32. if (cnt[u] < cnt[v]) {
  33. cnt[v] += cnt[u];
  34. par[u] = v;
  35. }
  36. else {
  37. cnt[u] += cnt[v];
  38. par[v] = u;
  39. }
  40.  
  41. return 1;
  42. }
  43.  
  44. bool in_mst[MAXM];
  45. int get(int del) {
  46. for (int i = 0; i < n; ++i) {
  47. par[i] = i;
  48. cnt[i] = 1;
  49. }
  50.  
  51. int c = 0;
  52. int ans = 0;
  53. for (int i = 0; i < m; ++i) {
  54. if (del == i) continue;
  55. if (merge(e[i].u, e[i].v)) {
  56. ++c;
  57. ans += e[i].c;
  58. if (del == -1) in_mst[i] = 1;
  59. }
  60. }
  61.  
  62. if (c != n - 1) return INF;
  63. else return ans;
  64. }
  65.  
  66. signed main() {
  67. ios_base::sync_with_stdio(0);
  68. cin.tie(0);
  69.  
  70. cin >> n >> m;
  71. for (int i = 0; i < m; ++i) {
  72. cin >> e[i].u >> e[i].v >> e[i].c;
  73. --e[i].u; --e[i].v;
  74. }
  75. sort(e, e + m, comp);
  76.  
  77. cout << "Cost: ";
  78. int ans1 = get(-1);
  79. if (ans1 == INF) cout << "-1\n";
  80. else cout << ans1 << '\n';
  81.  
  82. int ans2 = INF;
  83. for (int i = 0; i < m; ++i) {
  84. if (in_mst[i]) {
  85. ans2 = min(ans2, get(i));
  86. }
  87. }
  88.  
  89. cout << "Cost: ";
  90. if (ans2 == INF) cout << "-1\n";
  91. else cout << ans2 << '\n';
  92.  
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement