BZOJ 1878 hh necklace (Simple Mo team)

Description

HH has a necklace of various beautiful shells. HH believes that different shells bring good luck, so after each walk, he will take out one at random.
segment the shells and think about what they mean. HH is constantly collecting new shells, so his necklaces are getting longer and longer. One day, he suddenly proposed a
Question: How many different kinds of shells are contained in a certain section of shells? This question is difficult to answer. . . Because the necklace is really too long. So he only
I would like to ask you, wise man, to solve this problem.

Input

The first line: an integer N, representing the length of the necklace. 
The second line: N integers, representing the serial numbers of the shells in the necklace (the numbers are integers between 0 and 1000000). 
The third line: an integer M, indicating the number of HH queries. 
Next M lines: each line has two integers, L and R (1 ≤ L ≤ R ≤ N), indicating the interval of the query.
N ≤ 50000,M ≤ 200000。

Output

M lines, each with an integer, in turn represent the corresponding answers to the query.

Sample Input

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

Sample Output

2
2
4
 
Solution: Eh, Mo team's entry question is really very easy to understand. After learning it, we can only orz Mo team. It's too violent. Because of violence, Mo team can do a lot of range queries that only violence can do. The difficulty of the whole code is mainly In some details, but in fact, it is really impossible to carry it back~
code show as below:
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

struct node
{
    int l,r,id;
}q[200020];

int a[50050],cnt[1000010],n,m,sz,sum,ans[200020];

int block(int x)
{
    return (x+1)/sz;
}

int cmp(node a,node b)
{
    if(block(a.l)==block(b.l))
    {
        return a.r<b.r;
    }
    return a.l<b.l;
}

void add(int x)
{
    if(!cnt[a[x]])
    {
        sum++;
    }
    cnt[a[x]]++;
}

void del(int x)
{
    if(cnt[a[x]]==1)
    {
        sum--;
    }
    cnt[a[x]]--;
}

intmain ()
{
    scanf("%d",&n);
    sz=sqrt(n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d",&q[i].l,&q[i].r);
        q[i].id=i;
    }
    sort(q+1,q+m+1,cmp);
    int nowl=1,nowr=0;
    for(int i=1;i<=m;i++)
    {
        while(nowl<q[i].l) del(nowl++);
        while(nowl>q[i].l) add(--nowl);
        while(nowr<q[i].r) add(++nowr);
        while(nowr>q[i].r) del(nowr--);
        ans[q[i].id]=sum;
    }
    for(int i=1;i<=m;i++)
    {
        printf("%d\n",ans[i]);
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324689004&siteId=291194637