HH的项链

1878: [SDOI2009]HH的项链

Time Limit: 4 Sec  Memory Limit: 64 MB
Submit: 7536  Solved: 3711
[Submit][Status][Discuss]

Description

HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一
段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此他的项链变得越来越长。有一天,他突然提出了一
个问题:某一段贝壳中,包含了多少种不同的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只
好求助睿智的你,来解决这个问题。

Input

第一行:一个整数N,表示项链的长度。 
第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。 
第三行:一个整数M,表示HH询问的个数。 
接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。
N ≤ 50000,M ≤ 200000。

Output

M行,每行一个整数,依次表示询问对应的答案。

Sample Input

6
1 2 3 4 3 5
3
1 2
3 5
2 6

Sample Output

2
2
4

HINT

 

Source

莫队板子题
 
#include<cmath>
#include<queue>
#include<stack>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define FIN freopen("input.txt","r",stdin)
#define ll long long
#define mod 1000000007
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn = 1000000+5;
using namespace std;
ll a[maxn],b[maxn],cnt[maxn];
int unit,ans;
int res[maxn];
struct node
{
    int l,r,id;
    bool friend operator < (const node &u,const node &v)
    {
        if(u.l/unit!=v.l/unit)
            return u.l<v.l;
        return u.r<v.r;
    }
} p[maxn];
void add(int x)
{
    if(cnt[a[x]]==0)
        ans++;
    cnt[a[x]]++;
}
void remove(int x)
{
    if(cnt[a[x]]==1)
        ans--;
    cnt[a[x]]--;
}
int main()
{
    #ifndef ONLINE_JUDGE
        FIN;
       #endif

    int n,m;
    scanf("%d",&n);
    unit=sqrt(n);
    for(int i=1; i<=n; i++)
    {
        scanf("%I64d",&a[i]);
        b[i]=a[i];
    }
    scanf("%d",&m);
    for(int i=1; i<=m; i++)
    {
        scanf("%d %d",&p[i].l,&p[i].r);
        p[i].id=i;
    }
    sort(p+1,p+1+m);
    sort(b+1,b+1+n);
    for(int i=1; i<=n; i++) a[i] = lower_bound(b+1,b+1+n,a[i]) - b;
    int L=1,R=0;
    for(int i=1;i<=m;i++)
    {
        while(L>p[i].l) add(--L);
        while(L<p[i].l) remove(L++);
        while(R>p[i].r) remove(R--);
        while(R<p[i].r) add(++R);
        res[p[i].id]=ans;
    }
    for(int i=1;i<=m;i++)
        printf("%d\n",res[i]);
}
View Code

 

 

 

posted @ 2019-02-16 10:32  MengX  阅读(215)  评论(0编辑  收藏  举报

梦想不是空想