Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int maxn = 2e5 + 10;
- int next_idx[maxn];
- vector<int> segment_tree[3 * maxn];
- vector<int> merge_two_nodes(vector<int> & a, vector<int> & b) {
- int i = 0, j = 0;
- vector<int> c;
- while(i < (int) a.size() and j < (int) b.size()) {
- if(a[i] <= b[j]) {
- c.push_back(a[i]);
- i++;
- }
- else {
- c.push_back(b[j]);
- j++;
- }
- }
- while(i < (int) a.size()) {
- c.push_back(a[i]);
- i++;
- }
- while(j < (int) b.size()) {
- c.push_back(b[j]);
- j++;
- }
- return c;
- }
- void build_tree(int L, int R, int node) {
- if(L == R) {
- segment_tree[node].push_back(next_idx[L]);
- }
- else {
- int middle = (L + R) / 2;
- build_tree(L, middle, 2 * node);
- build_tree(middle + 1, R, 2 * node + 1);
- segment_tree[node] = merge_two_nodes(segment_tree[2 * node], segment_tree[2 * node + 1]);
- }
- }
- // L R i L R j L R
- int query(int L, int R, int node, int i, int j) {
- if(R < i or j < L) {
- return 0;
- }
- if(i <= L and R <= j) {
- return (int) segment_tree[node].size() - (lower_bound(segment_tree[node].begin(), segment_tree[node].end(), j + 1) - segment_tree[node].begin());
- }
- int middle = (L + R) / 2;
- return query(L, middle, 2 * node, i, j) + query(middle + 1, R, 2 * node + 1, i, j);
- }
- int main() {
- ios_base::sync_with_stdio(false);
- int n, q;
- cin >> n >> q;
- for(int i = 0; i < n; i++) {
- next_idx[i] = n;
- }
- vector<pair<int, int>> v(n);
- for(int i = 0; i < n; i++) {
- cin >> v[i].first;
- v[i].second = i;
- }
- sort(v.begin(), v.end());
- for(int i = 0; i < n - 1; i++) {
- if(v[i].first == v[i + 1].first) {
- next_idx[v[i].second] = v[i + 1].second;
- }
- }
- build_tree(0, n - 1, 1);
- for(int i = 0; i < q; i++) {
- int a, b;
- cin >> a >> b;
- a--; b--;
- cout << query(0, n - 1, 1, a, b) << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement