关于对牛客网2018年暑期第一场ACM第J题的理解(Different Integers)

这道题对刚入坑不久的我来说刚开始做比较难,后来研究透了,也没那么难了。

下面是题目:

Given a sequence of integers a1,a2,...,ana1,a2,...,an and q pairs of integers (l1,r1)(l1,r1),(l2,r2)(l2,r2), …, (lq,rq)(lq,rq), find count(l1,r1)(l1,r1), 
count(l2,r2)(l2,r2), …, count(lq,rq)(lq,rq) where count(i, j) is the number of different integers among a1,a2,...,ai,aj,aj+1,...,ana1,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 nn integers a1,a2,...,ana1,a2,...,an . 
The i-th of the following qq lines contains two integers liliand riri. 
输出描述: 
For each test case, print q integers which denote the result. 
备注 
* 1≤n,q≤1051≤n,q≤105 
* 1≤ai≤n1≤ai≤n 
* 1≤li,ri≤n1≤li,ri≤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 
输出 


3

这道题其实是可以用蔡队或者莫队的题解做,莫队对【l,r】区间做过很充分的解释,比较出名的就是两只袜子的题目,给出这个题目的链接,大家有时间也可以去看一下:https://www.cnblogs.com/Paul-Guderian/p/6933799.html这个博主写的非常好,推荐大家去阅读。

我接下来就用蔡队的方法,我对他的理解就是把原来的数组扩大两倍,用区间查询和区间修改的方法去做,然后建立了一个pre数组用来判断是不是第一次出现的,这道题比较难得地方就是对树状数组的理解。

下面附上代码:

#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;
}

如果还有不会的大家还需要专心研究下。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值