leanchec

wormsort.cpp

Oct 15th, 2024 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int MAXN=1e5+10;
  5.  
  6. int pai[MAXN], tam[MAXN];
  7.  
  8. int achar(int a){
  9.     if(pai[a]==a)return a;
  10.     return pai[a]=achar(pai[a]);
  11. }
  12.  
  13. void juntar(int a, int b){
  14.     a=achar(a);
  15.     b=achar(b);
  16.     if(a==b)return;
  17.     if(tam[a]<tam[b])swap(a, b);
  18.     pai[b]=a;
  19.     tam[a]+=tam[b];
  20. }
  21.  
  22. int main(){
  23.     ios_base::sync_with_stdio(0); cin.tie(0);
  24.     freopen("wormsort.in", "r", stdin);
  25.     freopen("wormsort.out", "w", stdout);
  26.     int n, m;
  27.     cin >> n >> m;
  28.     vector<vector<int>> grupos;
  29.     vector<bool> usou(n+3);
  30.  
  31.     vector<int> pos(n+3);
  32.     for(int i=1; i<=n; i++)
  33.         cin >> pos[i];
  34.  
  35.     vector<pair<int,pair<int,int>>> tuneis;
  36.  
  37.     for(int i=0; i<m; i++){
  38.         int w, a, b;
  39.         cin >> a >> b >> w;
  40.         tuneis.push_back({w, {a, b}});
  41.     }
  42.  
  43.     sort(tuneis.rbegin(), tuneis.rend());
  44.  
  45.     for(int i=1; i<=n; i++){
  46.         if(usou[i])continue;
  47.         vector<int> cur;
  48.  
  49.         int ptr=i;
  50.  
  51.         while(1){
  52.             if(usou[pos[ptr]])break;
  53.             usou[pos[ptr]]=true;
  54.             cur.push_back(pos[ptr]);
  55.             ptr=pos[ptr];
  56.         }
  57.  
  58.         grupos.push_back(cur);
  59.     }
  60.  
  61.     if(grupos.size()==n){
  62.         cout << -1 << endl;
  63.         return 0;
  64.     }
  65.  
  66.     int ini=0, fim=1000000000, resp;
  67.  
  68.     while(ini<=fim){
  69.         for(int i=1; i<=n; i++){
  70.             pai[i]=i;
  71.             tam[i]=1;
  72.         }
  73.         int mid=(ini+fim)>>1;
  74.  
  75.         for(auto t:tuneis){
  76.             if(t.first<mid)break;
  77.             juntar(t.second.first, t.second.second);
  78.         }
  79.  
  80.         bool teste=true;
  81.  
  82.         for(auto g:grupos){
  83.             for(int i=0; i<g.size(); i++){
  84.                 if(achar(g[0])!=achar(g[i])){
  85.                     teste=false;
  86.                     break;
  87.                 }
  88.             }
  89.             if(!teste)break;
  90.         }
  91.  
  92.         if(teste){
  93.             ini=mid+1;
  94.             resp=mid;
  95.         }
  96.         else fim=mid-1;
  97.     }
  98.  
  99.     cout << resp << endl;
  100.  
  101.     return 0;
  102. }
Add Comment
Please, Sign In to add comment