2018牛客多校第一场 J Different Integers

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

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld

题目描述

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 个数  q 次询问,每次询问给一个 l 与 r, 求a1~al , ar~an 中有多少个不同的数。

 

思路:

把给定的 n 个数延长一倍,然后问题就转换到了求连续区间的不同的数的个数。

对于第二个问题,我们可以考虑用树状数组做一下(听大佬们说还可以用主席树、线段树、莫队     orzorz……)

树状数组的思路就是 先将 q 次询问按照右端点从小到大排序,之后维护第 i 个数是否已经出现过, 如果没有就将端点 i 更新一下,同时保存一下当前 a[i] 的位置 i ;如果已经出现过,则将该数上一次出现的地方更新树状数组,同时再将当前位置更新树状数组,同样保存当前a[i] 的位置 i 。

 

上代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+10;
int tree[maxn],n,q,a[maxn],vis[maxn],ans[maxn];
struct node{
    int l,r,pos;
    bool operator<(const node&p)const {
        return r<p.r;
    }
}d[maxn];
inline int lowbit(int x) {return x&-x;}
inline void update(int x,int val){
    for (int i=x; i<maxn; i+=lowbit(i))  tree[i]+=val;
}
inline int Query(int x){
    int res=0;
    for (int i=x; i; i-=lowbit(i))
        res+=tree[i];
    return res;
}

int main(){
    while(scanf("%d%d",&n,&q)==2){
        memset(tree,0,sizeof(tree));
        memset(vis,0,sizeof(vis));
        memset(ans,0,sizeof(ans));
        for (int i=1; i<=n ;i++)  scanf("%d",&a[i]),a[i+n]=a[i];
        for (int l,r,i=1; i<=q; i++){
            scanf("%d%d",&l,&r);
//            if(l>r) swap(l,r);
            l+=n;
            d[i].l=r,d[i].r=l;
            d[i].pos=i;
        }
        sort(d+1,d+1+q);
        for (int i=1,j=1; i<=n+n && j<=q; i++){
            if(vis[a[i]]) update(vis[a[i]],-1);
            update(i,1);
            vis[a[i]]=i;
            while(j<=q && d[j].r==i){
                    ans[d[j].pos] = Query(d[j].r)-Query(d[j].l-1);
                    j++;
            }
        }
        for (int i=1; i<=q; i++)
            printf("%d\n",ans[i]);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值