牛客多校训练赛(一)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
using namespace std;
#define LL long long
#define lowbit(x) (x)&(-x)
const int MAXN = 2e5+10;
const int INF = 0x3f3f3f3f;

int n,m;
int a[MAXN],last[MAXN],h[MAXN],ans[MAXN];
struct node{
    int l,r,id;
}p[MAXN];
void init(){
    memset(a,0,sizeof(a));
    memset(last,0,sizeof(last));
    memset(h,0,sizeof(h));
    memset(ans,0,sizeof(ans));
}
bool cmp(node a,node b){
    return a.r < b.r;
}
void add(int x,int v){
    while(x<=2*n){
        h[x] += v;
        x += lowbit(x);
    }
}
int sum(int i){
    int sum = 0;
    while(i>0){
        sum += h[i];
        i -= lowbit(i);
    }
    return sum;
}
int main(){
    while(scanf("%d%d",&n,&m)!=EOF){
        init();
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            a[i+n] = a[i];
        }
        int u,v;
        for(int i=1;i<=m;i++){
            scanf("%d%d",&u,&v);
            p[i].l = v;
            p[i].r = u+n;
            p[i].id = i;
        }
        sort(p+1,p+m+1,cmp);//按照r从小到大排序
        int num = 1;
        for(int i=1;i<=2*n;i++){
            if(last[a[i]]){
                add(last[a[i]],-1);
            }
            add(i,1);
            last[a[i]] = i; 
            while(num<=m&&p[num].r<=i){
                ans[p[num].id] = sum(p[num].r) - sum(p[num].l-1);
                num++;
            }
        }
        for(int i=1;i<=2*n;i++){
            printf("%d ",h[i]);
        }cout<

 

你可能感兴趣的:(2018暑假多校补题,线段树&&树状数组)