luogu 3939 数颜色 - STL(vector)

传送门

分析:

虽然颜色种类很多,但是所有颜色个数之和n是一定的,这时候就可以使用vector对每个颜色维护一个坐标集合,空间只占n个。
对于查询L,R:直接一行: upper_bound(col[c].begin(), col[c].end(), r) - lower_bound(col[c].begin(), col[c].end(), l)
对于修改:

  1. 两种颜色相同,不管。
  2. 两种颜色不同:由于刚开始向每种颜色集合中加入坐标时,坐标是升序加入的,假设交换的是X和X+1,那么X变成X+1后整个集合仍然满足单调性,X+1同理,这样就可以省去排序的复杂度。

code

#include<bits/stdc++.h>
using namespace std;
namespace IO {
    template<typename T>
    inline void read(T &x) {
        T i = 0, f = 1;
        char ch = getchar();
        for(; (ch < '0' || ch > '9') && ch != '-'; ch = getchar());
        if(ch == '-') f = -1, ch = getchar();
        for(; ch >= '0' && ch <= '9'; ch = getchar()) i = (i << 3) + (i << 1) + (ch - '0');
        x = i * f;
    }
    template<typename T>
    inline void wr(T x) {
        if(x < 0) putchar('-'), x = -x;
        if(x > 9) wr(x / 10);
        putchar(x % 10 + '0');
    }
}using namespace IO;
const int N = 3e5 + 50;
vector<int> col[N];
int a[N], n, m;

int main(){
    read(n), read(m);
    for(int i = 1; i <= n; i++){
        int x; read(x); a[i] = x;
        col[x].push_back(i);
    }
    for(int i = 1; i <= m; i++){
        int opt; read(opt);
        if(opt == 1){
            int l, r, c; read(l), read(r), read(c);
            wr(upper_bound(col[c].begin(), col[c].end(), r) - lower_bound(col[c].begin(), col[c].end(), l));
            putchar('\n');
        }
        else {
            int x; read(x);
            if(a[x] != a[x + 1]){
                vector<int>::iterator it = lower_bound(col[a[x]].begin(), col[a[x]].end(), x);  (*it) = x + 1;
//				sort(it, col[a[x]].end());
                it = lower_bound(col[a[x + 1]].begin(), col[a[x + 1]].end(), x + 1);  (*it) = x;
//				sort(col[a[x + 1]].begin(), it + 1);
                swap(a[x], a[x + 1]);
            }
        }
    }
    return 0;
}
posted @ 2017-11-02 19:07  CzYoL  阅读(383)  评论(0编辑  收藏  举报