Advertisement
tepyotin2

P52 Wormhole Sort #992

Nov 6th, 2023
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. bool isDiag = false;
  5. int n, m;
  6. struct Edge{
  7.     int d, w;
  8.     Edge(){};
  9.     Edge(int d, int w): d(d), w(w) {}
  10. };
  11. int loc[100001];
  12. int component[100001];
  13. vector<Edge> edges[100001];
  14. void dfs(int curr, int label, int minW){
  15.     if(component[curr] == label){
  16.         return;
  17.     }
  18.     if(isDiag) cout << "[dfs] curr: " << curr << ", label: " << label << ", minW: " << minW << endl;
  19.     component[curr] = label;
  20.     for (Edge child: edges[curr])
  21.     {
  22.         if (child.w >= minW)
  23.         {
  24.             dfs(child.d, label, minW);
  25.         }
  26.     }
  27.    
  28. }
  29. bool valid(int minW){
  30.     memset(component, -1, sizeof(component));
  31.     int label = 0;
  32.     for (int i = 1; i <= n; i++)
  33.     {
  34.             if (component[i] < 0)
  35.             {
  36.                 dfs(i, label++, minW);
  37.             }
  38.     }
  39.     for (int i = 1; i <= n; i++)
  40.     {
  41.         if (component[i] != component[loc[i]])
  42.         {
  43.             if(isDiag) cout << "!!Invalid for component[" << i << "] label=" << component[i]
  44.                 << " vs. [" << loc[i] << "] label=" << component[loc[i]] << endl;
  45.             return false;
  46.         }
  47.     }
  48.     return true;
  49.    
  50. }
  51. int main(){
  52.     //isDiag = true;
  53.     freopen(  "wormsort.in", "r", stdin);
  54.    
  55.    
  56.     cin >> n >> m;
  57.     if(isDiag) cout << "n: " << n << ", m: " << m << endl;
  58.     for (int i = 1; i <= n; i++)
  59.     {
  60.         cin >> loc[i];
  61.     }
  62.     for (int i = 0; i < m; i++)
  63.     {
  64.         int a, b, w;
  65.         cin >> a >> b >> w;
  66.         edges[a].push_back(Edge(b, w));
  67.         edges[b].push_back(Edge(a, w));
  68.     }
  69.     int minW = 0, maxW = 1000000001;
  70.     while (minW != maxW)
  71.     {
  72.         int mid = (minW + maxW + 1) /2 ;
  73.         if(valid(mid)){
  74.              minW = mid;
  75.              if(isDiag) cout << "===Ok mid: " <<  mid << "====="<< endl;
  76.          }else{
  77.             maxW = mid - 1;
  78.          }
  79.     }
  80.     if (minW > 1e9)
  81.     {
  82.         minW = -1;
  83.     }
  84.    
  85.     if(!isDiag) freopen("wormsort.out", "w", stdout);
  86.     cout << minW << endl;
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement