牛客网暑期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<iostream>
#include<stdio.h>
#include<cmath>
#include<vector>
#include<string.h>
#include<algorithm>
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<b.r;
    }
}q[maxn];
int num[maxn];
void add(int x,int p)
{
    if(x==0) return ;
    for(;x<=n;x+=x&-x)
        num[x]+=p;
}
int query(int x)
{
    int ans=0;
    for(;x>=1;x-=x&-x)
        ans+=num[x];
    return ans;
}
 
int pre[maxn];
 
bool cmd(node a,node b){
    return a.id<b.id;
}
 
int main()
{
    int qq;
    while(~scanf("%d %d",&n,&qq)){
        memset(num,0,sizeof num);
        memset(pre,0,sizeof pre);
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            b[n-i+1]=a[i];
        }
        for(int i=n;i>=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;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值