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

Given a sequence of integers a 1 , a 2 , . . . , a n and q pairs of integers ( l 1 , r 1 ) , ( l 2 , r 2 ) , …, ( l q , r q ) , find count ( l 1 , r 1 ) ,
count ( l 2 , r 2 ) , …, count ( l q , r q ) where count(i, j) is the number of different integers among 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 integers a 1 , a 2 , . . . , a n .
The i-th of the following q lines contains two integers l i and r i .
输出描述:
For each test case, print q integers which denote the result.
备注
* 1 n , q 10 5
* 1 a i n
* 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<iostream>
#include<cstdio>
#include<map>
#include<cstring>
#include<algorithm>
#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.r<x2.r;
}
int 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;i<q;i++)
        {
            scanf("%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;i<q;i++)
        {
            for(;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;i<q;i++)
            printf("%d\n",ans[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/coldfresh/article/details/81122267
今日推荐