[HNOI2009] 梦幻布丁

[HNOI2009] 梦幻布丁

标签: 链表


题解

可以直接用链表启发式合并做。
合并的细节处理稍微有点麻烦。
假如需要变成另一种颜色的那个颜色的个数更多,那么就肯定不能直接合。
维护一个color数组代表,每个颜色在数组中存的位置。
这样交换color数组之后可以直接合并。

Code

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define REP(i,a,b) for(int i=(a),_end_=(b);i<=_end_;i++)
#define DREP(i,a,b) for(int i=(a),_end_=(b);i>=_end_;i--)
#define EREP(i,a) for(int i=start[(a)];i;i=e[i].next)
inline int read()
{
	int sum=0,p=1;char ch=getchar();
	while(!(('0'<=ch && ch<='9') || ch=='-'))ch=getchar();
	if(ch=='-')p=-1,ch=getchar();
	while('0'<=ch && ch<='9')sum=sum*10+ch-48,ch=getchar();
	return sum*p;
}

const int maxn=1e5+20;

int n,m,nxt[maxn],sz[maxn*10],col[maxn],start[maxn*10],color[maxn*10],fro[maxn*10];
int ans=0;

inline void init()
{
	n=read();
	m=read();
	REP(i,1,n)
	{
		col[i]=read();
		int x=col[i];
		if(col[i-1]!=x)ans++;
		if(!start[x])fro[x]=i;
		nxt[i]=start[x];
		start[x]=i;
		sz[x]++;
		color[x]=x;
	}
}


inline void doing()
{
	REP(i,1,m)
	{
		if(read()==2)printf("%d\n",ans);
		else
		{
			register int y=read(),x=read();
			if(x!=y)
			{
				if(sz[color[x]]<sz[color[y]])swap(color[x],color[y]);
				x=color[x];y=color[y];
				if(!sz[y])continue;
				sz[x]+=sz[y];sz[y]=0;
				for(int u=start[y];u;u=nxt[u])ans-=(col[u-1]==x)+(col[u+1]==x);
				for(int u=start[y];u;u=nxt[u])col[u]=x;
				nxt[fro[y]]=start[x];
				start[x]=start[y];

				start[y]=0;
				sz[y]=0;
				start[y]=0;
			}
		}
	}
}

int main()
{
	init();
	doing();
	return 0;
}


posted @ 2017-09-28 22:04  Deadecho  阅读(143)  评论(0编辑  收藏  举报