[BZOJ1483] [HNOI2009] 梦幻布丁
题目链接
BZOJ:https://lydsy.com/JudgeOnline/problem.php?id=1483.
洛谷:https://www.luogu.org/problemnew/show/P3201.
Solution
直接上线段树合并就好了,反正数据水,64MB也能过。
话说题解是啥链表启发式合并...还是线段树合并来的实在
#include<bits/stdc++.h>
using namespace std;
void read(int &x) {
x=0;int f=1;char ch=getchar();
for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-f;
for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';x*=f;
}
void print(int x) {
if(x<0) putchar('-'),x=-x;
if(!x) return ;print(x/10),putchar(x%10+48);
}
void write(int x) {if(!x) putchar('0');else print(x);putchar('\n');}
#define lf double
#define ll long long
const int maxn = 1e6+10;
const int inf = 1e9;
const lf eps = 1e-8;
int rt[maxn],n,m,ans;
#define mid ((l+r)>>1)
namespace SGT {
int ls[maxn<<2],rs[maxn<<2],sum[maxn<<2],seg;
bool L[maxn<<2],R[maxn<<2];
void update(int p) {
sum[p]=sum[ls[p]]+sum[rs[p]];L[p]=L[ls[p]],R[p]=R[rs[p]];
if(R[ls[p]]&&L[rs[p]]) sum[p]--;
}
void insert(int &p,int l,int r,int x) {
if(!p) p=++seg;
if(l==r) return L[p]=R[p]=1,sum[p]=1,void();
if(x<=mid) insert(ls[p],l,mid,x);
else insert(rs[p],mid+1,r,x);
update(p);
}
int query(int x) {return sum[x];}
int merge(int x,int y) {
if(!x||!y) return x+y;
int p=++seg;
ls[p]=merge(ls[x],ls[y]);
rs[p]=merge(rs[x],rs[y]);
update(p);return p;
}
}
int main() {
read(n),read(m);
for(int i=1,x;i<=n;i++) read(x),SGT::insert(rt[x],1,n,i);
for(int i=1;i<=1e6;i++) if(rt[i]) ans+=SGT::query(rt[i]);
for(int i=1;i<=m;i++) {
int op,x,y;read(op);
if(op==1) {
read(x),read(y);if(x==y) continue;int a,b;
ans-=a=(SGT::query(rt[x])+SGT::query(rt[y]));
rt[y]=SGT::merge(rt[x],rt[y]),rt[x]=0;
ans+=b=SGT::query(rt[y]);
} else write(ans);
}
return 0;
}