Josif_tepe

Untitled

Jan 21st, 2026
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int maxn = 105;
  4. const int INF = 1e9;
  5. int sz[maxn], idx[maxn];
  6. void init() {
  7.     for(int i = 0; i < maxn; i++) {
  8.         idx[i] = i;
  9.         sz[i] = 1;
  10.     }
  11. }
  12.  
  13. int root(int x) {
  14.     while(x != idx[x]) {
  15.         idx[x] = idx[idx[x]];
  16.         x = idx[x];
  17.     }
  18.     return x;
  19. }
  20.  
  21. void unite(int A, int B) {
  22.     int rootA = root(A);
  23.     int rootB = root(B);
  24.    
  25.     if(rootA != rootB) {
  26.         if(sz[rootA] < sz[rootB]) {
  27.             idx[rootA] = idx[rootB];
  28.             sz[rootB] += sz[rootA];
  29.         }
  30.         else {
  31.             idx[rootB] = idx[rootA];
  32.             sz[rootA] += sz[rootB];
  33.         }
  34.     }
  35. }
  36.  
  37. bool check(int A, int B) {
  38.     return root(A) == root(B);
  39. }
  40.  
  41.  
  42. int main() {
  43.     ios_base::sync_with_stdio(false);
  44.     int n, m;
  45.     cin >> n >> m;
  46.    
  47.     vector<pair<int, pair<int, int>>> graph;
  48.    
  49.     for(int i = 0; i < m; i++) {
  50.         int a, b, c;
  51.         cin >> a >> b >> c;
  52.        
  53.         graph.push_back({c, {a, b}});
  54.     }
  55.    
  56.     sort(graph.begin(), graph.end());
  57.     vector<pair<int, int>> MST;
  58.     int mst = 0;
  59.     init();
  60.     for(int i = 0; i < m; i++) {
  61.         int C = graph[i].first;
  62.         int A = graph[i].second.first;
  63.         int B = graph[i].second.second;
  64.        
  65.         if(!check(A, B)) {
  66.             unite(A, B);
  67.             mst += C;
  68.             MST.push_back({A, B});
  69.         }
  70.     }
  71.    
  72.     int mst2 = INF;
  73.     for(int i = 0; i < (int) MST.size(); i++) {
  74.         int tmp = 0;
  75.         int cnt = 0;
  76.         init();
  77.        
  78.         for(int j = 0; j < (int) graph.size(); j++) {
  79.             int C = graph[j].first;
  80.             int A = graph[j].second.first;
  81.             int B = graph[j].second.second;
  82.            
  83.             if(A == MST[i].first and B == MST[i].second) continue;
  84.            
  85.             if(!check(A, B)) {
  86.                 unite(A, B);
  87.                 tmp += C;
  88.                 cnt++;
  89.             }
  90.            
  91.         }
  92.         if(cnt == n - 1) {
  93.             mst2 = min(mst2, tmp);
  94.         }
  95.     }
  96.    
  97.     cout << mst << endl;
  98.     cout << mst2 << endl;
  99.     return 0;
  100. }
  101.  
Advertisement
Add Comment
Please, Sign In to add comment