Problem
刚开始,每个数一个块。
有两个操作:0 x y 合并x,y所在的块
1 x 查询第x大的块
Solution
用并查集合并时,把原来的大小删去,加上两个块的大小和。
Notice
非旋转Treap一直错。。。
Code
旋转Treap(非旋转Treap总是TLE...)
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define sqz main
#define ll long long
#define reg register int
#define rep(i, a, b) for (reg i = a; i <= b; i++)
#define per(i, a, b) for (reg i = a; i >= b; i--)
#define travel(i, u) for (reg i = head[u]; i; i = edge[i].next)
const int INF = 1e9, N = 400000;
const double eps = 1e-6, phi = acos(-1.0);
ll mod(ll a, ll b) {if (a >= b || a < 0) a %= b; if (a < 0) a += b; return a;}
ll read(){ ll x = 0; int zf = 1; char ch; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
if (ch == '-') zf = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;}
void write(ll y) { if (y < 0) putchar('-'), y = -y; if (y > 9) write(y / 10); putchar(y % 10 + '0');}
int fa[N + 5], T[N + 5], point = 0, root;
int Find(int x)
{
if (fa[x] != x) fa[x] = Find(fa[x]);
return fa[x];
}
struct node
{
int Val[N + 5], Level[N + 5], Size[N + 5], Son[2][N + 5], Num[N + 5];
inline void up(int u)
{
Size[u] = Size[Son[0][u]] + Size[Son[1][u]] + Num[u];
}
inline void Newnode(int &u, int v)
{
u = ++point;
Level[u] = rand(), Val[u] = v;
Size[u] = Num[u] = 1, Son[0][u] = Son[1][u] = 0;
}
inline void Lturn(int &x)
{
int y = Son[1][x]; Son[1][x] = Son[0][y], Son[0][y] = x;
Size[y] = Size[x]; up(x); x = y;
}
inline void Rturn(int &x)
{
int y = Son[0][x]; Son[0][x] = Son[1][y], Son[1][y] = x;
Size[y] = Size[x]; up(x); x = y;
}
void Insert(int &u, int t)
{
if (u == 0)
{
Newnode(u, t);
return;
}
Size[u]++;
if (t == Val[u]) Num[u]++;
else if (t > Val[u])
{
Insert(Son[0][u], t);
if (Level[Son[0][u]] < Level[u]) Rturn(u);
}
else if (t < Val[u])
{
Insert(Son[1][u], t);
if (Level[Son[1][u]] < Level[u]) Lturn(u);
}
}
void Delete(int &u, int t)
{
if (!u) return;
if (Val[u] == t)
{
if (Num[u] > 1)
{
Num[u]--, Size[u]--;
return;
}
if (Son[0][u] * Son[1][u] == 0) u = Son[0][u] + Son[1][u];
else if (Level[Son[0][u]] < Level[Son[1][u]]) Rturn(u), Delete(u, t);
else Lturn(u), Delete(u, t);
}
else if (t > Val[u]) Size[u]--, Delete(Son[0][u], t);
else Size[u]--, Delete(Son[1][u], t);
}
int Find_num(int u, int t)
{
if (!u) return 0;
if (t <= Size[Son[0][u]]) return Find_num(Son[0][u], t);
else if (t <= Size[Son[0][u]] + Num[u]) return u;
else return Find_num(Son[1][u], t - Size[Son[0][u]] - Num[u]);
}
}Treap;
int sqz()
{
int n = read(), m = read();
rep(i, 1, n) fa[i] = i, Treap.Insert(root, 1), T[i] = 1;
while (m--)
{
int op = read();
if (!op)
{
int x = Find(read()), y = Find(read());
if (x != y)
{
Treap.Delete(root, T[x]), Treap.Delete(root, T[y]);
fa[x] = y;
T[y] += T[x];
Treap.Insert(root, T[y]);
}
}
else
{
int x = read();
printf("%d
", Treap.Val[Treap.Find_num(root, x)]);
}
}
}