Different Integers(Nowcoder多校训练第一场J题)(树状数组+离线)

Given a sequence of integers a1,a2,...,an a 1 , a 2 , . . . , a n and q pairs of integers (l1,r1) ( l 1 , r 1 ) , (l2,r2) ( l 2 , r 2 ) , …, (lq,rq) ( l q , r q ) , find count (l1,r1) ( l 1 , r 1 ) ,
count (l2,r2) ( l 2 , r 2 ) , …, count (lq,rq) ( l q , r q ) where count(i, j) is the number of different integers among a1,a2,...,ai,aj,aj+1,...,an a 1 , a 2 , . . . , a i , a j , a j + 1 , . . . , a n .
输入描述:
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 n integers a1,a2,...,an a 1 , a 2 , . . . , a n .
The i-th of the following q q lines contains two integers li l i and ri r i .
输出描述:
For each test case, print q integers which denote the result.
备注
* 1n,q105 1 ≤ n , q ≤ 10 5
* 1ain 1 ≤ a i ≤ n
* 1li,rin 1 ≤ l i , r i ≤ n
* The number of test cases does not exceed 10.
示例1:
输入
3 2
1 2 1
1 2
1 3
4 1
1 2 3 4
1 3
输出
2
1
3

还是自己太菜了,比赛快结束了才想到了做法,幸好还是过了吧。

思路:此题和我一年前做的一道cf题很像(题目链接),思想是一样的。这题我把数组复制一遍放到右边,那么数组大小就是2n了,把询问按照r排序。

#include
#include
#include
#include
#include
#define maxx 200005
using namespace std;
int n,q;
int a[maxx];
int mp[100005];
struct node
{
    int l,r;
    int index;
}p[100005];
int cmp(node x1,node x2)
{
    return x1.rint ans[100005];
int pre[maxx];
int c[maxx];
void change(int x,int p)
{
    for(;x<=n;x+=x&(-x))c[x]+=p;
}
int ask(int x)
{
    int ans=0;
    for(;x;x-=x&-x)ans+=c[x];
    return ans;
}
int main()
{
    while(scanf("%d%d",&n,&q)==2)
    {
        memset(c,0,sizeof(c));
        memset(pre,0,sizeof(pre));
        memset(mp,0,sizeof(mp));
        int cal=n;
        for(int i=1;i<=n;i++)
            scanf("%d",a+i),a[i+cal]=a[i];
        int l,r;
        for(int i=0;iscanf("%d%d",&l,&r);
            p[i].l=r;
            p[i].r=cal+l;
            p[i].index=i;
        }
        sort(p,p+q,cmp);
        n<<=1;
        for(int i=1;i<=n;i++)
        {
            pre[i]=mp[a[i]];
            mp[a[i]]=i;
        }//相当于一个链表串起来了,只有有相同的书才连起来
        int j=1;
        for(int i=0;ifor(;j<=p[i].r;j++)
            {
                if(pre[j])change(pre[j],-1);
                change(j,1);
            }////随着询问,不断把数往右移,而不会影响答案。
            ans[p[i].index]=ask(p[i].r)-ask(p[i].l-1);
        }
        for(int i=0;iprintf("%d\n",ans[i]);
    }
    return 0;
}

你可能感兴趣的:(树状数组,离线处理)