洛谷-1903【模板】 [国家集训队]数颜色 / 维护队列

题目描述
墨墨购买了一套N支彩色画笔(其中有些颜色可能相同),摆成一排,你需要回答墨墨的提问。墨墨会向你发布如下指令:
1、 Q L R代表询问你从第L支画笔到第R支画笔中共有几种不同颜色的画笔。
2、 R P Col 把第P支画笔替换为颜色Col。
为了满足墨墨的要求,你知道你需要干什么了吗?
输入格式
第1行两个整数N,M,分别代表初始画笔的数量以及墨墨会做的事情的个数。
第2行N个整数,分别代表初始画笔排中第i支画笔的颜色。
第3行到第2+M行,每行分别代表墨墨会做的一件事情,格式见题干部分。
输出格式
对于每一个Query的询问,你需要在对应的行中给出一个数字,代表第L支画笔到第R支画笔中共有几种不同颜色的画笔。

输入输出样例
输入 #1
6 5
1 2 3 4 5 5
Q 1 4
Q 2 6
R 1 2
Q 1 4
Q 2 6

输出 #1
4
4
3
4

说明/提示
对于30%的数据,n,m≤10000
对于60%的数据,n,m≤50000
对于所有数据,n,m≤133333
所有的输入数据中出现的所有整数均大于等于1且不超过10^6。
本题可能轻微卡常数

可修改莫队算法的模板题

#include<bits/stdc++.h>
using namespace std;
const int N=1000010;
int n,m;
int c[N];
struct node1{
    int l,r,x,id;
};
node1 q[N];
struct node2{
    int x,y;
};
node2 ch[N];
int totq=0,totch=0,unit,ans[N],tot=0,sum[N];
int cmp(const node1 &a,const node1 &b){
    if (a.l/unit!=b.l/unit) return a.l/unit<b.l/unit;
    else if (a.r/unit!=b.r/unit) return a.r/unit<b.r/unit;
    else return a.x<b.x;
}
void update(int wz,int z){
    if (z==-1){
        sum[c[wz]]--;
        if (!sum[c[wz]]) tot--;
    }else{
        sum[c[wz]]++;
        if(sum[c[wz]]==1) tot++;
    }
}
void change(int bh,int l,int r){
    if (ch[bh].x>=l&&ch[bh].x<=r) update(ch[bh].x,-1);   //删除从前的影响
    swap(c[ch[bh].x],ch[bh].y);
    if (ch[bh].x>=l&&ch[bh].x<=r) update(ch[bh].x,1);   //添加影响
}
void solve(){
    int l=1,r=0,now=0;
    for (int i=1;i<=m;i++){
        while (r<q[i].r) update(r+1,1),r++;
        while (r>q[i].r) update(r,-1),r--;
        while (l>q[i].l) update(l-1,1),l--;
        while (l<q[i].l) update(l,-1),l++;
        while (now<q[i].x) change(now+1,l,r),now++;
        while (now>q[i].x) change(now,l,r),now--;
        ans[q[i].id]=tot;
    }
}
int main(){
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++) scanf("%d",&c[i]);
    for (int i=1;i<=m;i++){
        char s[4];
        int x,y;
        scanf("%s %d %d",s,&x,&y);
        if (s[0]=='Q'){
            totq++;
            q[totq].l=x; q[totq].r=y;
            q[totq].x=totch;
            q[totq].id=totq;
        }else{
            totch++;
            ch[totch].x=x;
            ch[totch].y=y;
        }
    }
    unit=(int)pow(n,0.666666);
    sort(q+1,q+1+totq,cmp);
    solve();
    for (int i=1;i<=totq;i++) printf("%d\n",ans[i]);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值