`

poj 2985 并查集+树状数组求第k大数

    博客分类:
  • acm
阅读更多
#include <stdio.h>
#include <string.h>
#define lowbit(i) i&(-i)
#define maxn 300000
using namespace std;
int a[maxn],c[maxn],p[maxn];
int fd(int x)
{
    return x==p[x] ? x :fd(p[x]);
}
void update(int x,int val)
{
    while(x<=maxn)
    {
        c[x]+=val;
        x+=lowbit(x);
    }
}
int find_kth(int k)
{
    int ans = 0,cur = 0;
    for(int i=20;i>=0;i--)
    {
        ans+=(1<<i);
        if(ans>maxn||cur+c[ans]>=k)
            ans-=(1<<i);
        else
            cur+=c[ans];
    }
    return ans+1;
}
int main()
{
    int n,m,k,l,t,q,x,y;
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        p[i]=i;
        a[i]=1;
    }
    update(1,n);
    int num = n;
    while(m--)
    {
        scanf("%d",&q);
        if(q==0)
        {
            scanf("%d %d",&x,&y);
            x = fd(x);
            y = fd(y);
            if(x==y) continue;
            update(a[x],-1);
            update(a[y],-1);
            update(a[x]+a[y],1);
            p[y]=x;
            a[x]+=a[y];
            num--;
        }
        else
        {
            scanf("%d",&k);
            printf("%d\n",find_kth(num-k+1));
        }
    }
    return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics