码迷,mamicode.com
首页 > 其他好文 > 详细

莫队学习总结 && P1903 [国家集训队]数颜色 / 维护队列

时间:2018-11-02 23:57:08      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:add   work   ||   pre   ios   string   define   scanf   总结   

关于时间复杂度

对于多维莫队的复杂度差不多\(O(n^{\frac{2k-1}{k}})\)
摘自zhihu大佬

奇偶分类优化

return a.l == b.l ? (a.l & 1) ? a.r<b.r: a.r>b.r  :  a.l < b.l;

这样能快是因为指针移到右边后不用再跳回左边,而跳回左边后处理下一个块又要跳回右边,这样能减少一半操作,理论上能快一倍

思路

好久的题目了,之前其实只会点不修改莫队
对带修改的不大会,也就做过这一个题目
今天重新做了一边,算是有了新的认识了

其实是在不修改的莫对上加了一个时间戳
修改时的时候和时间一起移动就好了
虽然复杂度会更高(所以一般莫队待修改就很慢了)

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define FOR(i,a,b) for(int i=a;i<=b;++i)
using namespace std;
const int maxn=5e4+7;
const int maxm=1e6+7;
char s;
int n,m,A,B,a[maxn],belong[maxn],vis[maxm],ans;
struct node {
    int x,y,id,tim,ans;
}Q[maxn];
struct modify {
    int id,v;
}C[maxn];
bool cmp1(const node &a,const node &b) {
    return belong[a.x]==belong[b.x] ? (belong[a.y]==belong[b.y] ? a.tim<b.tim : a.y<b.y) : a.x<b.x;
}
bool cmp2(const node &a,const node &b) {
    return a.id<b.id;
}
int read() {
    int x=0,f=1;char s=getchar();
    for(;s<'0'||s>'9';s=getchar()) if(s=='-') f=-1;
    for(;s>='0'&&s<='9';s=getchar()) x=x*10+s-'0';
    return x*f;
}
void add(int x) {
    if(!vis[a[x]]) ++ans;
    ++vis[a[x]];
}
void delet(int x) {
    --vis[a[x]];
    if(!vis[a[x]]) --ans;
}
void work(int x,int i){
    if(Q[i].x<=C[x].id && C[x].id<=Q[i].y) {
        --vis[a[C[x].id]];
        ++vis[C[x].v];
        if(!vis[a[C[x].id]]) --ans;
        if(vis[C[x].v]==1) ++ans;
    }
    swap(C[x].v,a[C[x].id]);
}

int main() {
    n=read(),m=read();
    int k=sqrt(n)*7;
    FOR(i,1,n) a[i]=read();
    FOR(i,1,n) belong[i]=(i-1)/k+1;
    FOR(i,1,m) {
        scanf("%s",&s);
        if(s=='Q') {
            Q[++A].id=A;
            Q[A].tim=B;
            Q[A].x=read();
            Q[A].y=read();
        } else {
            C[++B].id=read();
            C[B].v=read();
        }
    }
    sort(Q+1,Q+1+A,cmp1);
    int l=1,r=0,ttt=0;
    FOR(i,1,A) {
        while(Q[i].x<l) add(--l);
        while(Q[i].x>l) delet(l++);
        while(Q[i].y>r) add(++r);
        while(Q[i].y<r) delet(r--);

        while(Q[i].tim>ttt) work(++ttt,i);
        while(Q[i].tim<ttt) work(ttt--,i);

        Q[i].ans=ans;
    }
    sort(Q+1,Q+1+A,cmp2);
    FOR(i,1,A) cout<<Q[i].ans<<"\n";
    return 0;
}

莫队学习总结 && P1903 [国家集训队]数颜色 / 维护队列

标签:add   work   ||   pre   ios   string   define   scanf   总结   

原文地址:https://www.cnblogs.com/lovedsr/p/9898685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!