您的位置:首页 > 其它

Poj 2985 The k-th Largest Group

2013-03-04 17:31 417 查看
题目:http://poj.org/problem?id=2985

题目:合并集合,求元素第k多的集合有多少个元素。

合并集合很简单用并查集即可。

这里我主要想说一下如何用树状数组并在线查询数集内第k小(大)的数。

方法是:用树状数组记录数集中某个数出现次数,每输入一个数,相当于将该数出现次数加1,对应到树状数组中就相当于insert(t, 1),统计的时候,可以利用树状数组的求和,这样我们求第k小的数可以用二分法来查询,求第k大的数可以转换成第k小的数来做。

具体方法看本题及对应的代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
using namespace std;

int father[200005];//并查集所在集合的代表元素
int son[200005];//并查集所在集合的元素的个数
int times[200005];//times[i]表示son[]中值为i的元素的出现次数

int n;
int g;

int findset(int a)
{
if(a == father[a])
{
return a;
}
father[a] = findset(father[a]);
return father[a];

}
//求2的K次幂
int lowbit(int t)
{
return t&(-t);
}
//更新树状数组
void update(int t,int x)
{
while(t<=n)
{
times[t] += x;
t+=lowbit(t);

}
}
//获取前N项和
int getSum(int t)
{
int sum = 0;
while(t>0)
{
sum+=times[t];
t-=lowbit(t);
}
return sum;
}
//二分法
int query(int k)
{
int low = 1;
int high = n;//注意这里不是g
while(low < high)
{
int mid = (low + high)/2;
if(k<=getSum(mid))
{
high = mid;
}
else
{
low = mid + 1;
}
}
return low;
}

int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int m;
int p;
int x,y;
int k;

while(scanf(" %d %d",&n,&m)!=EOF)
{
for(int i=1; i<200005; i++)
{
father[i] = i;
son[i] = 1;
}

//初始化 times[1] = n
memset(times,0,sizeof(times));
g = n;
update(1,n);

for(int i=0; i<m; i++)
{
scanf(" %d",&p);
if(p == 0)
{
scanf(" %d %d",&x,&y);
//将y所在的集合并入到x所在的集合中
x = findset(x);
y = findset(y);
if(x!=y)
{

if(son[x] == son[y])
{
update(son[x],-2);
}
else
{
update(son[x],-1);
update(son[y],-1);
}
update(son[x] + son[y],1);
son[y] += son[x];
son[x] = 0;
father[x] = y;
g--;//合并以后的堆的个数
}
}
else if(p == 1)
{
scanf(" %d",&k);
//把求son[]中第K大的数转换为求son[]中第g-K+1小的数
printf("%d\n",query(g-k+1));
}
}
}
return 0;
}
参考:http://hi.baidu.com/agosits/item/aa777fd8f12ac7f9b3f7770f
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: