洛谷 P1903 [国家集训队]数颜色 带修改的莫队算法

题目:
洛谷 P1903

分析:很显然的待修改的莫队。第一次打,感觉有点丑。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>

const int maxn=10005;
const int tot_color=1e6+2;
using namespace std;

struct node{
    int id,l,r,x,ans;
//id表示询问位置,l,r表示询问系数,x表示前面有多少个修改,ans表示答案
}q[maxn];

struct te{
    int x,col,pre;
//x表示修改的地址,col表示修改后颜色,pre表示修改前颜色
}c[maxn];

int n,m,i,ans,l,r,cnt,block,change,x,y;
int a[maxn],sum[tot_color],belong[maxn];

bool cmp(node x,node y)
{
    if (belong[x.l]==belong[y.l])
    {
        if (belong[x.r]==belong[y.r]) return x.x<y.x;
        return x.r<y.r; 
    }
    return x.l<y.l;
}

void updata(int x,int c)
{
    if (c==1)
    {
        if (sum[a[x]]==0) ans++;
        sum[a[x]]++;
    }
    else
    {
        sum[a[x]]--;
        if (sum[a[x]]==0) ans--;
    }

}

void updata1(int x,int c)
{
    if ((x<q[i].l) || (x>q[i].r)) return;
    if (c==1)
    {
        if (sum[a[x]]==0) ans++;
        sum[a[x]]++;
    }
    else
    {
        sum[a[x]]--;
        if (sum[a[x]]==0) ans--;
    }

}
bool cmp1(node x,node y)
{
    return x.id<y.id;
}

int main()
{
    scanf("%d%d",&n,&m);
    for (i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    char op[1]; 
    for (i=1;i<=m;i++)
    {
        scanf("%s",op);
        scanf("%d%d",&x,&y);
        if (op[0]=='R')
        { 
            change++;
            c[change].x=x;
            c[change].col=y;
        }
        else
        {
            cnt++;
            q[cnt].id=i;
            q[cnt].l=x;
            q[cnt].r=y; 
            q[cnt].x=change;
        }
    }
    block=trunc(sqrt(n));
    for (i=1;i<=n;i++) belong[i]=(i-1)/block+1; 
    sort(q+1,q+1+cnt,cmp);  
    l=r=1;
    ans=1;
    change=0; 
    sum[a[1]]++;    

    for (i=1;i<=cnt;i++)
    {
        for (r;r<q[i].r;r++) updata(r+1,1);
        for (r;r>q[i].r;r--) updata(r,0);
        for (l;l<q[i].l;l++) updata(l,0);
        for (l;l>q[i].l;l--) updata(l-1,1);
        for (change;change<q[i].x;change++) 
        {
            updata1(c[change+1].x,0);
            c[change+1].pre=a[c[change+1].x];
            a[c[change+1].x]=c[change+1].col;
            updata1(c[change+1].x,1); 
        }
        for (change;change>q[i].x;change--)
        {
            updata1(c[change].x,0);
            a[c[change].x]=c[change].pre;
            updata1(c[change].x,1);
        }
        q[i].ans=ans;
    }
    sort(q+1,q+1+cnt,cmp1);
    for (i=1;i<=cnt;i++)
    {
        printf("%d\n",q[i].ans);
    }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值