AT_abc372_e [ABC372E] K-th Largest Connected Components

· · 题解

题目大意

给你 q 个操作。

  1. 连接 u 和 v
  2. 查询 u 所在的连通块中编号第 k 大的点

    题解

    因为 k\leq10 ,所以可以对于每一个联通块,我们都可以维护一个大小为 10 的数组来记前 10 个编号大的点

至于连边操作,显然用并查集维护,两个连通块用双指针合并

#include<bits/stdc++.h>
using namespace std;
#define int long long
int fa[1100000],n,q,siz[1100000];
int f[1100000][21];
int getfa(int x){
    if(fa[x]==x){
        return x;
    }
    return fa[x]=getfa(fa[x]);
}
void merge(int x,int y){
    int i=1,j=1,t=1;
    int temp[21];
    memset(temp,0,sizeof(temp));
    while(i<=siz[getfa(x)] and j<=siz[getfa(y)] and t<=10){
        if(f[getfa(x)][i]>f[getfa(y)][j]){
            temp[t++]=f[getfa(x)][i++];
        }else{
            temp[t++]=f[getfa(y)][j++];
        }
    }
    while(t<=10 and i<=siz[getfa(x)]){
        temp[t++]=f[getfa(x)][i++];
    }
    while(t<=10 and j<=siz[getfa(y)]){
        temp[t++]=f[getfa(y)][j++];
    }
    siz[getfa(x)]+=siz[getfa(y)];
    siz[getfa(x)]=min(siz[getfa(x)],10ll);
    for(int k=1;k<=siz[getfa(x)];k++){
        f[getfa(x)][k]=temp[k];
    }
    fa[getfa(y)]=getfa(x);
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>q;
    for(int i=1;i<=n;i++){
        fa[i]=i;
        f[i][1]=i;
        siz[i]=1;
    }
    for(int i=1;i<=q;i++){
        int opt,x,y;
        cin>>opt>>x>>y;
        if(opt==1 and getfa(x)!=getfa(y)){
            merge(x,y);
        }
        if(opt==2){
            if(siz[getfa(x)]<y){
                cout<<-1<<'\n';
            }else{
                cout<<f[getfa(x)][y]<<'\n';
            }
        }
    }
    return 0;
}