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

题目

题目描述 

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.

 

题意:

给你n个数字,给你查询l,r,让你得出1-l 加上r-n里不同的数有几个。

 

POINT:

把数组扩充两倍,那么问题就变成了连续一段区间内不同的数有几个了。

那么可以用树状数组+离线做。

 

#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 2e5+55;
int n;
int a[maxn];
int b[maxn];
struct node
{
    int l,r;
    int id;
    int ans;
    friend bool operator < (node a, node b)
    {
        return a.r=1;x-=x&-x)
        ans+=num[x];
    return ans;
}
 
int pre[maxn];
 
bool cmd(node a,node b){
    return a.id=1;i--){
            b[n+n-i+1]=a[i];
        }
        for(int i=1;i<=qq;i++){
            int l,r;scanf("%d%d",&l,&r);
            q[i].l=n-l+1;
            q[i].id=i;
            q[i].r=n+n-r+1;
        }
        n=2*n;
        sort(q+1,q+1+qq);
        int now = 1;
        for(int i=1;i<=n&&now<=qq;i++){
            add(i,1);
            add(pre[b[i]],-1);
            pre[b[i]]=i;
            while(q[now].r==i&&now<=qq){
                q[now].ans=query(q[now].r)-query(q[now].l-1);
                now++;
            }
        }
        sort(q+1,q+1+qq,cmd);
        for(int i=1;i<=qq;i++){
            printf("%d\n",q[i].ans);
        }
    }
    return 0;
}

 

 

 

你可能感兴趣的:(其他,树状数组)