For this problem Wormhole Sort following is my approach(earlier I came up with similar approach as given in Internal Solution using DSU but thought that it would unnecessarily make things complex):
Sort the womholes in decreasing order on basis of their width. Maintain a variable ct, which indicates number of misplaced positions of cows. Also mark that position in array a for future use. Then traverse from Wormhole with largest width and for each wormhole check if it connects positions which are misplaced and if it does then unmark that position and decrement ct. Stop at wormhole where ct becomes ZERO and print corresponding width.
My code
#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("wormsort.in", "r", stdin);
freopen("wormsort.out", "w", stdout);
int n,m;cin>>n>>m;
int a[n]={0},ct=0;
for(int i=0;i<n;i++){
int x;cin>>x;
if(x!=i+1){
++ct;
a[i]=1;
}
}
if(ct==0){
cout<<"-1";
return 0;
}
vector<pair<int,pair<int,int>>> v;
for(int i=0;i<m;i++){
int x,y,w;cin>>x>>y>>w;
v.push_back({w,{x-1,y-1}});
}
sort(v.rbegin(),v.rend());
for(int i=0;i<m;i++){
if(a[v[i].second.first]){
--ct;
a[v[i].second.first]=0;
}
if(a[v[i].second.second]){
--ct;
a[v[i].second.second]=0;
}
if(ct==0){
cout<<v[i].first;
break;
}
}
return 0;
}
All testcases are passing except 5th one.