题意:1~n个猫,有合并操作,有询问操作,合并两只猫所在的集合,询问第K大的集合。

分析:合并操作用并查集,用size维护,询问操作用Treap。注意优化,不能刚开始就把所有size = 1放到名次树中,是1的不做处理,而是不够的时候返回一个1;

 #include <cstdio>
#include <algorithm>
#include <cstring> using namespace std; struct Node {
Node *ch[];
int r;
int v;
int s;
Node(int v):v(v) {ch[]=ch[] = NULL;r=rand();s=;}
bool operator < (const Node& rhs) const {
return r < rhs.r;
} int cmp(int x) const {
if(x==v) return -;
return x < v ? : ;
} void maintain() {
s = ;
if(ch[]!=NULL) s+=ch[]->s;
if(ch[]!=NULL) s+=ch[]->s;
} }*root; void rotate(Node* &o,int d)
{
Node *k=o->ch[d^];
o->ch[d^]=k->ch[d];
k->ch[d]=o;
o->maintain();
k->maintain();
o=k;
}
void insert(Node* &o,int v)//可插入重复值
{
if(o==NULL) o=new Node(v);
else
{
int d=v < o->v? :;
insert(o->ch[d],v);
if(o->ch[d]->r > o->r)
rotate(o,d^);
}
o->maintain();
}
void remove(Node* &o,int v)
{
int d=o->cmp(v);
if(d==-)
{
Node *u=o;
if(o->ch[] && o->ch[])
{
int d2= o->ch[]->r < o->ch[]->r ?:;
rotate(o,d2);
remove(o->ch[d2],v);
}
else
{
if(o->ch[]==NULL) o=o->ch[];
else o=o->ch[];
delete u;
}
}
else remove(o->ch[d],v);
if(o) o->maintain();
} int kth(Node *o,int k)//返回第k大的值,不是第k小
{
if(o==NULL || k<= || k> o->s) return ;
int s = (o->ch[]==NULL)?:o->ch[]->s;
if(k==s+) return o->v;
else if(k<=s) return kth(o->ch[],k);
else return kth(o->ch[],k-s-);
} const int maxn=+;
int n,m;
int father[maxn],size[maxn]; int Find_Set(int x) {
if(father[x]!=x)
father[x] = Find_Set(father[x]);
return father[x];
} int main()
{
//freopen("in.txt","r",stdin);
root = NULL;
for(int i=;i<maxn;i++) {
father[i] = i;
size[i] = ;
}
scanf("%d%d",&n,&m);
//for(int i=0;i<n;i++)
//insert(root,1);
while(m--) {
int cmp;
scanf("%d",&cmp);
if(cmp==) {
int u,v;
scanf("%d%d",&u,&v);
int fx = Find_Set(u);
int fy = Find_Set(v);
if(fx!=fy)
{
if(size[fx]!=) remove(root,size[fx]);
if(size[fy]!=) remove(root,size[fy]);
father[fy] = fx;
size[fx]+=size[fy];
insert(root,size[fx]);
}
}
else {
int k;
scanf("%d",&k);
printf("%d\n",kth(root,k));
}
} return ;
}

最新文章

  1. JVM内存管理
  2. [转]Redmine 配置163邮箱
  3. EDNS
  4. OC基础—多态(超级简单)
  5. xss跨站攻击测试代码
  6. GTP V0 和 GTP V1
  7. grep sed
  8. BrowserSync,调试利器--自动刷新(转
  9. CodeForce 7 B - Memory Manager(模拟)
  10. Tomcat从零开始(十一)WebappLoader概述
  11. python中print,return和yield的区别
  12. ActionInvoker
  13. Asp.Net MVC 之 Autofac 初步使用2 集成mvc 属性注入以及自动注入
  14. 笔记:Spring Cloud Ribbon 客户端负载均衡
  15. CF932E Team Work
  16. Centos7单主机部署 LAMP + phpmyadmin 服务
  17. hadoop-1
  18. JAXP操作xml
  19. ubuntu 常用设置
  20. Linux内核设计与实现第五周读书笔记

热门文章

  1. windows同时安装python2和python3两个版本
  2. Data Guard 管理原理
  3. Oracle RAC集群添加节点
  4. 抓包来看ftp状态码
  5. (Frontend Newbie) Web三要素(一)
  6. 【STM32学习笔记】STM32f407 使用4*4矩阵键盘
  7. Whu 1603——Minimum Sum——————【单个元素贡献、滑窗】
  8. 【软件安装】Xshell出现要继续使用此程序必须应用到最新的更新或使用新版本
  9. jquery点滴总结
  10. 项目搭建系列之二:SpringMVC框架下配置MyBatis