BZOJ 1483 [HNOI2009]梦幻布丁

链表+启发式合并

黄学长题解(orz):http://hzwer.com/2858.html

附:
pos[i]表示i颜色(数据中的正确颜色)在链表中存储为pos[i]。那么交换pos[i]和pos[j]就是交换他们存储的颜色。反正最后合成完一定是一个完全的链表,且这个链表是被pos[y]指向的,这样就可以了,复杂度每一次操作均摊logn

#include<cstdio>
#include<algorithm>
#define N 100005
#define C 1000005
using namespace std;
int c[C], head[C], next[C], siz[C], pos[C];
int in()
{
    int r=0;
    char c=getchar();
    while(c<'0'||c>'9')c=getchar();
    while(c>='0'&&c<='9')r=r*10+c-'0',c=getchar();
    return r;
}
int main()
{
    int n, m, ans=0;
    n=in(); m=in();
    for(int i = 1; i <= n; i++)
    {
        c[i]=in();
        if(c[i]!=c[i-1])ans++;
        next[i]=head[c[i]];
        head[c[i]]=i;
        pos[c[i]]=c[i];
        siz[c[i]]++;
    }
    while(m--)
    {
        int op, x, y, end;
        op=in();
        if(op==2)printf("%d\n",ans);
        else
        {
            x=in(); y=in();
            if(siz[pos[x]]>siz[pos[y]])swap(pos[x],pos[y]);
            x=pos[x]; y=pos[y];
            if(siz[x]==0 || x==y){continue;}//要判掉,否则会有奇怪的事情发生 
            for(int i = head[x]; i; i=next[i])
            {
                if(c[i-1]==y)ans--;
                if(c[i+1]==y)ans--;
                end=i;
            }
            for(int i = head[x]; i; i=next[i])
                c[i]=y;
            siz[y]+=siz[x];
            siz[x]=0;
            next[end]=head[y];
            head[y]=head[x];
            head[x]=0;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值