bzoj1483 [HNOI2009]梦幻布丁

 

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

Sample Output

3
1

 

正解:链表启发式合并。

1:将两个队列合并,有若干队列,总长度为n,直接合并,最坏O(N),
2:启发式合并呢?
每次我们把短的合并到长的上面去,O(短的长度)
咋看之下没有多大区别,
下面让我们看看均摊的情况:
1:每次O(N)
2:每次合并后,队列长度一定大于等于原来短的长度的两倍。
这样相当于每次合并都会让短的长度扩大一倍以上,
最多扩大logN次,所以总复杂度O(NlogN),每次O(logN)。
然后对于此题
我们先求出原序列的答案
每一种颜色搞一条链把该色结点串起来,记录下链条尾结点
把一种颜色的染成另一种,很简单把它合并过去,然后处理下对于答案的影响
但是。。。
比如把1染成2,但是s[1]>s[2],这时我们应该将2合并到1的链后面,但是会遇到一个麻烦的问题,就是这个链头是接1下的,也就是说以后找颜色2,发现没有颜色2只有颜色1。。。

于是我们应该开一个数组f,表示我们寻找一种颜色时,实际应该找哪个颜色下的链,遇到上面那种情况要交换f[1]和f[2]。

——hzwer

复杂度证明很神奇。。感觉自己用链表还不熟啊。。

 

 1 //It is made by wfj_2048~
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <cstdio>
 7 #include <vector>
 8 #include <cmath>
 9 #include <queue>
10 #include <stack>
11 #include <map>
12 #include <set>
13 #define inf (1<<30)
14 #define il inline
15 #define RG register
16 #define ll long long
17 #define File(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout)
18 
19 using namespace std;
20 
21 int size[1000010],head[1000010],st[1000010],f[1000010],nt[100010],a[100010],n,m,tot,ans;
22 
23 il int gi(){
24     RG int x=0,q=1; RG char ch=getchar(); while ((ch<'0' || ch>'9') && ch!='-') ch=getchar();
25     if (ch=='-') q=-1,ch=getchar(); while (ch>='0' && ch<='9') x=x*10+ch-48,ch=getchar(); return q*x;
26 }
27 
28 il void solve(RG int x,RG int y){
29     for (RG int i=head[x];i;i=nt[i]){
30     if (a[i+1]==y) ans--; if (a[i-1]==y) ans--;
31     }
32     for (RG int i=head[x];i;i=nt[i]) a[i]=y;
33     nt[st[x]]=head[y],head[y]=head[x];
34     size[y]+=size[x],head[x]=st[x]=size[x]=0;
35     return;
36 }
37 
38 il void work(){
39     n=gi(),m=gi(); RG int x,y; for (RG int i=1;i<=n;++i) a[i]=gi();
40     for (RG int i=1;i<=n;++i){
41     f[a[i]]=a[i],size[a[i]]++;
42     if (a[i]!=a[i-1]) ans++;
43     if (!head[a[i]]) st[a[i]]=i;
44     nt[i]=head[a[i]],head[a[i]]=i;
45     }
46     for (RG int i=1;i<=m;++i){
47     RG int type=gi();
48     if (type==1){
49         x=gi(),y=gi(); if (x==y) continue;
50         if (size[f[x]]>size[f[y]]) swap(f[x],f[y]);
51         x=f[x],y=f[y]; if (!size[x]) continue; solve(x,y);
52     }else printf("%d\n",ans);
53     }
54     return;
55 }
56 
57 int main(){
58     File("pudding");
59     work();
60     return 0;
61 }

 

posted @ 2017-02-09 19:37  wfj_2048  阅读(242)  评论(0编辑  收藏  举报