牛客网暑期ACM多校训练营(第一场)J Different Integers 【离线】【树状数组】

链接:https://www.nowcoder.com/acm/contest/139/J
来源:牛客网
 

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld

题目描述

Given a sequence of integers a1, a2, ..., an and q pairs of integers (l1, r1), (l2, r2), ..., (lq, rq), find count(l1, r1), count(l2, r2), ..., count(lq, rq) where count(i, j) is the number of different integers among a1, a2, ..., ai, aj, aj + 1, ..., an.

输入描述:

The input consists of several test cases and is terminated by end-of-file.
The first line of each test cases contains two integers n and q.
The second line contains n integers a1, a2, ..., an.
The i-th of the following q lines contains two integers li and ri.

输出描述:

For each test case, print q integers which denote the result.

示例1

输入

复制

3 2
1 2 1
1 2
1 3
4 1
1 2 3 4
1 3

输出

复制

2
1
3

备注:

* 1 ≤ n, q ≤ 105
* 1 ≤ ai ≤ n
* 1 ≤ li, ri ≤ n
* The number of test cases does not exceed 10.

数组倍增,两段连在一起,这样询问的不连续区间即可转换为连续区间;

#include<bits/stdc++.h>
using namespace std;
const int MAX = 1e6 + 7;

struct node{
    int l, r, id;
    bool operator < (const node &a) const{
        if(r == a.r)
            return l < a.l;
        return r < a.r;
    }
} T[MAX];

int a[MAX], c[MAX], vis[MAX], ans[MAX];

int lowbit(int x){
    return x & -x;
}

void add(int pos, int v){
    while(pos < MAX){
        c[pos] += v;
        pos += lowbit(pos);
    }
}

int query(int pos){
    int res = 0;
    while(pos){
        res += c[pos];
        pos -= lowbit(pos);
    }
    return res;
}

int main(){
    int n, m;
    while(scanf("%d%d", &n, &m) != EOF){
        memset(c, 0, sizeof c);
        memset(vis, 0, sizeof vis);
        for(int i = 1; i <= n; i++){
            scanf("%d", &a[i]);
            a[i + n] = a[i];
        }
        for(int i = 1, x, y; i <= m; i++){
            scanf("%d%d", &x, &y);
            T[i].l = y;
            T[i].r = x + n;
            T[i].id = i;
        }
        sort(T + 1, T + m + 1);
        for(int i = 1, j = 1; i <= n * 2 && j <= m; i++){
            if(vis[a[i]])
                add(vis[a[i]], -1);
            add(i, 1);
            vis[a[i]] = i;
            while(j <= m && T[j].r <= i){
                ans[T[j].id] = query(T[j].r) - query(T[j].l - 1);
                j++;
            }
        }
        for(int i = 1; i <= m; i++)
            printf("%d\n", ans[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/head_hard/article/details/81157056
今日推荐