题解:P3224 [HNOI2012] 永无乡
双倍经验:AT_abc372_e [ABC372E] K-th Largest Connected Components。
介绍一种时间复杂度正确的 pb_ds 解法。
很明显这两种操作都能用平衡树 + 并查集维护。
但是手写 FHQ or Splay 太麻烦了,还不如打线段树合并呢,怎么办?
这时候就要用到我们亲爱的 pb_ds 中的 rb_tree_tag 了。
rb_tree_tag 用法。
假设你已经学会了以上操作。
然后先建立一个并查集,并把每个节点
代码:
for(int i=1;i<=n;i++){
cin>>a[i];
f[i]=i;
tr[i].insert({a[i],i});
}
对于操作一(或初始加边),设
代码:
int fx=find(f[x]),fy=find(f[y]);
if(fx==fy) continue;
f[fy]=fx;
while(tr[fy].size()){
PII it=*tr[fy].find_by_order(0);
tr[fx].insert(it);
tr[fy].erase(tr[fy].upper_bound(it));
}
对于操作
代码:
int fx=find(f[x]);
if(tr[fx].size()<y) cout<<-1<<endl;
else cout<<(*tr[fx].find_by_order(y-1)).se<<endl;
细心的朋友可能在 oi-wiki 中发现了一个叫做 join(x) 的函数,实际上这玩意在实际应用中基本 P 用没有,直接忽略就行。
join(x)函数需要保证并入树的键的值域与被并入树的键的值域不相交(也就是说并入树内所有值必须全部大于 / 小于当前树内的所有值),否则会抛出join_error异常。如果要合并两棵值域有交集的树,需要将一棵树的元素一一插入到另一棵树中。
——oi-wiki
然后我们发现过不了,原因是暴力合并有可能会被卡到
代码:
int fx=find(f[x]),fy=find(f[y]);
if(fx==fy) continue;
if(tr[fx].size()<tr[fy].size()) f[fx]=fy,swap(fx,fy);
else f[fy]=fx;
while(tr[fy].size()){
PII it=*tr[fy].find_by_order(0);
tr[fx].insert(it);
tr[fy].erase(tr[fy].upper_bound(it));
}
然后我们就过了。
代码:
#include<bits/stdc++.h>
#include<bits/extc++.h>
#define PII pair<int,int>
#define fi first
#define se second
using namespace std;
using namespace __gnu_pbds;
const int N=1e5+1;
tree<PII,null_type,less_equal<PII>,rb_tree_tag,tree_order_statistics_node_update>tr[N];
int n,m,q,x,y,a[N],f[N];
char op;
int find(int x){
if(f[x]==x) return x;
return f[x]=find(f[x]);
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
f[i]=i;
tr[i].insert({a[i],i});
}
while(m--){
cin>>x>>y;
int fx=find(x),fy=find(y);
if(fx==fy) continue;
if(tr[fx].size()<tr[fy].size()) f[fx]=fy,swap(fx,fy);
else f[fy]=fx;
while(tr[fy].size()){
PII it=*tr[fy].find_by_order(0);
tr[fx].insert(it);
tr[fy].erase(tr[fy].upper_bound(it));
}
}
cin>>q;
while(q--){
cin>>op>>x>>y;
if(op=='Q'){
int fx=find(f[x]);
if(tr[fx].size()<y) cout<<-1<<endl;
else cout<<(*tr[fx].find_by_order(y-1)).se<<endl;
}
else{
int fx=find(f[x]),fy=find(f[y]);
if(fx==fy) continue;
if(tr[fx].size()<tr[fy].size()) f[fx]=fy,swap(fx,fy);
else f[fy]=fx;
while(tr[fy].size()){
PII it=*tr[fy].find_by_order(0);
tr[fx].insert(it);
tr[fy].erase(tr[fy].upper_bound(it));
}
}
}
}