【題解】AtCoder ABC174F – Range Set Query

【題目敘述】https://atcoder.jp/contests/abc174/tasks

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n, q, c[500005], l[500005], r[500005], p[500005], bit[500005], ans[500005];
vector <int> v;

bool cmp(int x, int y){
    return r[x] <= r[y];
}
void update(int x, int d){
    while (x <= n){
        bit[x] += d;
        x += x & (-x);
    }
}
int query(int x){
    int ret = 0;
    while (x){
        ret += bit[x];
        x -= x & (-x);
    }
    return ret;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> q;
    for (int i = 1; i <= n; i++){
        cin >> c[i];
    }
    for (int i = 0; i < q; i++){
        cin >> l[i] >> r[i];
        v.push_back(i);
    }
    int pos = 0;
    sort(v.begin(), v.end(), cmp);
    for (auto i:v){
        for (int j = pos+1; j <= r[i]; j++){
            if (p[c[j]]) update(p[c[j]], -1);
            update(j, 1);
            p[c[j]] = j;
        }
        pos = r[i];
        ans[i] = query(r[i])-query(l[i]-1);
    }
    for (int i = 0; i < q; i++){
        cout << ans[i] << "\n";
    }
}

分享本文 Share with friends