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

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

题目描述

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.
思路:
按l从小到大排序,扫描过的l相应的权值a[l],
找到a[l]在最右边出现的位置。
每次询问的答案就是扫到l是出现的不同值的个数
加上右边从n扫到r的不同值的个数减去r~n之间在
1~l中出现过的数字,用树状数组维护即可。

代码:

#include
using namespace std;
const int maxn=1e5+10;
struct node
{
    int l,r,id;
}q[maxn];
int n,Q;
int a[maxn],L[maxn],R[maxn],S[maxn],ans[maxn],bit[maxn];
bool vis[maxn];
bool cmp(const node &x,const node &y) {return x.l0)
    {
        cnt+=bit[i];
        i-=i&-i;
    }
    return cnt;
}
void init()
{
    memset(L,0,sizeof(L));
    memset(R,0,sizeof(R));
    memset(bit,0,sizeof(bit));
    memset(S,0,sizeof(S));
}
int main()
{
    while(~scanf("%d%d",&n,&Q))
    {
        init();
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        for(int i=1;i<=Q;i++)
        {
            q[i].id=i;
            scanf("%d%d",&q[i].l,&q[i].r);
        }
        sort(q+1,q+Q+1,cmp);
        memset(vis,0,sizeof(vis));
        for(int i=1;i<=n;i++)
        {
            if(!vis[a[i]])
            {
                L[i]=1;//从左边开始扫描i位置的数字之前是否出现过
                vis[a[i]]=1;
            }
        }
        memset(vis,0,sizeof(vis));
        for(int i=n;i>=1;i--)
        {
            if(!vis[a[i]])
            {
                R[a[i]]=i;//R[a[i]]表示从右边起最先出a[i]的位置
                vis[a[i]]=1;
                S[i]++;
            }
            S[i]+=S[i+1];
        }
        int l=0,cnt=0;
        for(int i=1;i<=Q;i++)
        {
            node e=q[i];
            while(l

 

你可能感兴趣的:(脑力激活)