UVA - 12345 Dynamic len(set(a[L:R])) (带修改莫队)

Dynamic len(set(a[L:R]))

 

题目链接:https://vjudge.net/problem/UVA-12345

题目大意:给出长度为n的数组,有m个操作 ,Q x y 表示查询 [x , y-1] 区间里有多少种不同的数字, M x y 表示把 a[x] 修改为y

思路:带修改的莫队。在原来的莫队上,加了修改。其余不变,在查询 l,r,pos,中再加一个m,表示当前查询之前的修改次数。

按照pos,r和m排序,其余不变,pos r相等时让m小的排在前面。转移的时候对修改操作执行或者恢复。

代码:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
const int N=1000005;
int a[N],e[N],ans,b[N],c[N],l,r;
struct que
{
    int l,r,pos,id,m;
}qu[N];
struct modi
{
    int pos,x,pre;
}mo[N];
bool cmp(que a,que b)
{
    if(a.pos==b.pos)
    {
        if(a.r==b.r)
            return a.m<b.m;
        return a.r<b.r;
    }
    return a.pos<b.pos;
}
void update(int x,int p)
{
    if(x==0) return;
    if(c[x]) ans--;
    c[x]+=p;
    if(c[x]) ans++;
}
void modify(int x,int p)
{
    if(x>=l&&x<=r)
    {
        update(a[x],-1);
        update(p,1);
    }
    a[x]=p;
}
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    int p=pow(n,0.666666);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),e[i]=a[i];
    int tot=0,cnt=0;
    char s;
    int x,y;
    for(int i=0;i<m;i++)
    {
        scanf(" %c%d%d",&s,&x,&y);
        x++;
        if(s=='Q')
        {
            qu[tot].l=x,qu[tot].r=y;
            qu[tot].pos=x/p,qu[tot].id=tot;
            qu[tot++].m=cnt;
        }
        else
        {
            mo[++cnt].pos=x,mo[cnt].x=y;
            mo[cnt].pre=e[x];
            e[x]=y;
        }
    }
    sort(qu,qu+tot,cmp);
    l=0,r=0,ans=0;
    int cn=0;
    for(int i=0;i<tot;i++)
    {
        while(cn<qu[i].m) modify(mo[cn+1].pos,mo[cn+1].x),cn++;
        while(cn>qu[i].m) modify(mo[cn].pos,mo[cn].pre),cn--;
        while(l>qu[i].l) update(a[--l],1);
        while(l<qu[i].l) update(a[l++],-1);
        while(r>qu[i].r) update(a[r--],-1);
        while(r<qu[i].r) update(a[++r],1);
        b[qu[i].id]=ans;
    }
    for(int i=0;i<tot;i++)
        printf("%d\n",b[i]);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值