A - Monkey King
可以可並堆,但是我蔡
考慮DSU+啟發式合併,發現做完了
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int fa[N];
priority_queue<int> q[N];
int n,m;
int find(int x){
return x==fa[x]?x:fa[x]=find(fa[x]);
}
void merge(int x,int y){
fa[x]=y;
while(!q[x].empty()){
q[y].push(q[x].top());
q[x].pop();
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
while(cin>>n){
for(int i=1,in;i<=n;i++){
cin>>in;
fa[i]=i;
while(!q[i].empty()) q[i].pop();
q[i].push(in);
}
cin>>m;
for(int i=1;i<=m;i++){
int x,y;
cin>>x>>y;
x=find(x),y=find(y);
if(x==y){
cout<<"-1\n";
continue;
}
if(q[x].size()>q[y].size()) swap(x,y);
int X=q[x].top()/2,Y=q[y].top()/2;
q[x].pop(),q[y].pop();
merge(x,y);
q[y].push(X),q[y].push(Y);
cout<<q[y].top()<<"\n";
}
}
}