牛客网暑期ACM多校训练营(第一场).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.
#include<bits/stdc++.h>
using namespace std;
int block[100010],a[100010],out[100010],sum[100010];
int n,m,i,j,t,L,R,ans;
struct ask
{
    int l,r,id;
}q[100010];
 
bool cmp(ask x,ask y)
{
    if(block[x.l]!=block[y.l]) return block[x.l]<block[y.l];
    else return x.r<y.r;
}

void inc(int x)
{
    if(sum[x]==0)ans++;sum[x]++;
} 

void dec(int x)
{
    sum[x]--;if(sum[x]==0)ans--;
}
 
signed main()
{
    while(~scanf("%d%d",&n,&m))
    {
        memset(sum,0,sizeof sum);
        for(i=1;i<=n;i++)scanf("%d",&a[i]),block[i]=i/sqrt(n);
        for(i=1;i<=m;i++)scanf("%d%d",&q[i].l,&q[i].r),q[i].id=i;
        sort(q+1,q+1+m,cmp);
        L=0,R=n+1;ans=0;
        for(i=1;i<=m;i++)
        {
            while(L<q[i].l)
                L++,inc(a[L]);
            while(R>q[i].r)
                R--,inc(a[R]);
            while(L>q[i].l)
                dec(a[L]),L--;
            while(R<q[i].r)
                dec(a[R]),R++;
            out[q[i].id]=ans;
        }
        for(i=1;i<=m;i++)printf("%d\n",out[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xxxxxm1/article/details/81253313
今日推荐