如果每次将数量小的颜色,替换为数量大的颜色,那么由于一个格子,最多被换logn次,复杂度即为O(n log n)。
所以,我们就用f[x]记录:每个初始颜色为x的颜色,的当前值为多少。(因为根据sum大小换过了颜色)
而对于不同颜色的遍历,我们可以用类似链式前向星(或链表)的东西来存储。
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5,M=1e6+5;
int n,m,opt,x,y,ans;
int a[N],f[M],sum[M],first[M],head[M],next[N];
inline void change(int x,int y)
{
for (register int i=head[x]; i; i=next[i])
{
if (a[i+1]==y) ans--;
if (a[i-1]==y) ans--;
}
for (register int i=head[x]; i; i=next[i]) a[i]=y;
next[first[x]]=head[y]; head[y]=head[x]; sum[y]+=sum[x];
head[x]=0; first[x]=0; sum[x]=0;
}
int main(){
scanf("%d%d",&n,&m);
for (register int i=1; i<=n; ++i)
{
scanf("%d",&a[i]);
sum[a[i]]++; f[a[i]]=a[i];
if (a[i]!=a[i-1]) ans++;
if (!first[a[i]]) first[a[i]]=i;
next[i]=head[a[i]],head[a[i]]=i;
}
while (m--)
{
scanf("%d",&opt);
if (opt==1)
{
scanf("%d%d",&x,&y);
if (x==y) continue;
if (sum[f[x]]>sum[f[y]]) swap(f[x],f[y]);
if (!sum[f[x]]) continue;
change(f[x],f[y]);
}
else printf("%d\n",ans);
}
return 0;
}