[HNOI2009]梦幻布丁

用并查集维护
在代表元素中保存当前段的颜色(),和左右端点(
再用一个桶维护每种颜色的所有段
当且仅当要合并两段颜色相同时进行合并,并更新左右端点
对于每个桶用list 维护,再进行启发式合并,这里偷懒直接用了vector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<cstdio>
#include<vector>
using namespace std;
const int N=100050;
int fa[N],w[N],cnt,s[N],t[N],n,m;
vector<int> f[N*10];
inline int read()
{
register int x=0,t=1;
register char ch=getchar();
while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if (ch=='-') {t=-1;ch=getchar();}
while (ch>='0'&&ch<='9') {x=x*10+ch-48;ch=getchar();}
return x*t;
}
int find(int x) {return fa[x]==x?x:fa[x]=find(fa[x]);}
void unite(int u,int v)
{
if (!u||!v) return;
u=find(u),v=find(v);
if (w[u]!=w[v]) return;else cnt--;
fa[v]=u,s[u]=min(s[u],s[v]),t[u]=max(t[u],t[v]);
}
void update()
{
int u=read(),v=read();
if (u==v) return;
while (!f[u].empty())
{
int x=f[u].back();f[u].pop_back();
if (find(x)!=x) continue;else w[x]=v;
int st=s[x],ed=t[x];
if (st>1) unite(st-1,st);
if (ed<n) unite(ed,ed+1);
if (find(x)==x) f[v].push_back(x);
}
}
int main()
{
n=cnt=read(),m=read();
for(int i=1;i<=n;i++) w[i]=read(),fa[i]=i;
for(int i=1;i<=n;i++) s[i]=t[i]=i;
for(int i=1;i<n;i++) unite(i,i+1);
for(int i=1;i<=n;i++)
if (i==find(i))
f[w[i]].push_back(i);
for(int i=1;i<=m;i++)
{
int opt=read();
if (opt==1) update();
if (opt==2) printf("%d\n",cnt);
}
return 0;
}