题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1483
Description
N个布丁摆成一行,进行M次操作.每次将某个颜色的布丁全部变成另一种颜色的,然后再询问当前一共有多少段颜色.例如颜色分别为1,2,2,1的四个布丁一共有3段颜色.
Input
第一行给出N,M表示布丁的个数和好友的操作次数. 第二行N个数A1,A2...An表示第i个布丁的颜色从第三行起有M行,对于每个操作,若第一个数字是1表示要对颜色进行改变,其后的两个整数X,Y表示将所有颜色为X的变为Y,X可能等于Y. 若第一个数字为2表示要进行询问当前有多少段颜色,这时你应该输出一个整数. 0
Output
针对第二类操作即询问,依次输出当前有多少段颜色.
Sample Input
4 3
1 2 2 1
2
1 2 1
2
1 2 2 1
2
1 2 1
2
Sample Output
3
1
1
代码如下:
#include <bits/stdc++.h>
#define rep(i,s,t) for(int (i)=(s); (i)<=(t); (i)++)
#define ms(a,b) memset((a),(b),sizeof((a)))
using namespace std;
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 1e6+10;
int head[maxn], next[maxn], a[maxn], tail[maxn], sum = 0;
int sz[maxn], fa[maxn];
void insert(int x, int pos)
{
next[pos] = head[x];
head[x] = pos;
if(!tail[x]) tail[x] = pos;
}
void merge(int x, int y)
{
if(x==y) return;
if(sz[fa[x]]>sz[fa[y]]) swap(fa[x],fa[y]);
if(sz[fa[x]]==0) return;
x = fa[x], y = fa[y];
for(int i = head[x]; i; i = next[i])
{
if(a[i-1]==y) sum--;
if(a[i+1]==y) sum--;
}
for(int i = head[x]; i; i = next[i])
a[i] = y;
next[tail[y]] = head[x];
tail[y] = tail[x];
head[x] = tail[x] = 0;
sz[y] += sz[x];
sz[x] = 0;
}
int main()
{
int n, m;
scanf("%d%d",&n,&m);
rep(i,1,n)
{
scanf("%d",&a[i]);
fa[a[i]] = a[i];
if(a[i]!=a[i-1]) sum++;
sz[a[i]]++;
insert(a[i],i);
}
rep(i,1,m)
{
int p, x, y;
scanf("%d",&p);
if(p==2)
printf("%d\n",sum);
else
scanf("%d%d",&x,&y), merge(x,y);
}
}