[HNOI2009] 梦幻布丁

如果每次将数量小的颜色,替换为数量大的颜色,那么由于一个格子,最多被换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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值