链表+启发式合并
黄学长题解(orz):http://hzwer.com/2858.html
附:
pos[i]表示i颜色(数据中的正确颜色)在链表中存储为pos[i]。那么交换pos[i]和pos[j]就是交换他们存储的颜色。反正最后合成完一定是一个完全的链表,且这个链表是被pos[y]指向的,这样就可以了,复杂度每一次操作均摊logn
#include<cstdio>
#include<algorithm>
#define N 100005
#define C 1000005
using namespace std;
int c[C], head[C], next[C], siz[C], pos[C];
int in()
{
int r=0;
char c=getchar();
while(c<'0'||c>'9')c=getchar();
while(c>='0'&&c<='9')r=r*10+c-'0',c=getchar();
return r;
}
int main()
{
int n, m, ans=0;
n=in(); m=in();
for(int i = 1; i <= n; i++)
{
c[i]=in();
if(c[i]!=c[i-1])ans++;
next[i]=head[c[i]];
head[c[i]]=i;
pos[c[i]]=c[i];
siz[c[i]]++;
}
while(m--)
{
int op, x, y, end;
op=in();
if(op==2)printf("%d\n",ans);
else
{
x=in(); y=in();
if(siz[pos[x]]>siz[pos[y]])swap(pos[x],pos[y]);
x=pos[x]; y=pos[y];
if(siz[x]==0 || x==y){continue;}//要判掉,否则会有奇怪的事情发生
for(int i = head[x]; i; i=next[i])
{
if(c[i-1]==y)ans--;
if(c[i+1]==y)ans--;
end=i;
}
for(int i = head[x]; i; i=next[i])
c[i]=y;
siz[y]+=siz[x];
siz[x]=0;
next[end]=head[y];
head[y]=head[x];
head[x]=0;
}
}
}