牛客网暑期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<bits/stdc++.h>
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.l<y.l;}
void add(int i)
{
    while(i<=n)
    {
        bit[i]+=1;
        i+=i&-i;
    }
}
int sum(int i)
{
    int cnt=0;
    while(i>0)
    {
        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<e.l)
            {
                l++;
                if(L[l]) cnt++;
                if(L[l]&&R[a[l]]) add(R[a[l]]);
            }
            ans[e.id]=cnt+S[e.r]-sum(n)+sum(e.r-1);
        }
        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、付费专栏及课程。

余额充值