HH 有一串由各種漂亮的貝殼組成的項鍊。HH 相信不同的貝殼會帶來好運,所以每次散步完後,他都會隨意取出一段貝殼,思考它們所表達的含義。HH 不斷地收集新的貝殼,因此,他的項鍊變得越來越長。有一天,他突然提出了一個問題:某一段貝殼中,包含了多少種不同的貝殼?這個問題很難回答……因爲項鍊實在是太長了。於是,他只好求助睿智的你,來解決這個問題。
輸入輸出格式
輸入格式:
第一行:一個整數N,表示項鍊的長度。
第二行:N 個整數,表示依次表示項鍊中貝殼的編號(編號爲0 到1000000 之間的整數)。
第三行:一個整數M,表示HH 詢問的個數。
接下來M 行:每行兩個整數,L 和R(1 ≤ L ≤ R ≤ N),表示詢問的區間。
輸出格式:
M 行,每行一個整數,依次表示詢問對應的答案。
輸入輸出樣例
輸入樣例#1: 複製
6 1 2 3 4 3 5 3 1 2 3 5 2 6
輸出樣例#1: 複製
2 2 4
說明
數據範圍:
對於100%的數據,N <= 500000,M <= 500000。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#define inf 0x3f3f3f3f
#define ll long long
const int maxn = 2e7+5;
using namespace std;
int a[maxn],ans[maxn];int block;
struct node{
int l,r,step;
}pp[maxn];
#define G(a) putchar(a+48)
inline void write(int s){
if (s<0) G(-3),s=-s;
if (s>9) write(s/10);
G(s%10);
}
inline int gi(){
register int x=0,f=1;register char ch=getchar();
while(ch<'0'||ch>'9')f=ch=='-'?-1:f,ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
bool cmp(node a,node b)
{
return a.l/block == b.l/block? (a.l/block)&1 == 1?a.r<b.r:a.r>b.r:a.l < b.l;//分塊排序不用分塊會超時
}
int res ;//記錄不符合標記的數目
int book[maxn];
void reves(int k,int v)//k是當前要更新的位置v代表1爲增加-1減少
{
int u = a[k];
if(v == 1)
{
if(book[u] == 0)
{
res++;
}
book[u]++;
}
else
{
if(book[u] == 1)
{
res--;
}
book[u]--;
}
}
int main()
{
int n,q;
n = gi();
//scanf("%d",&n);
res = 0;
block = sqrt(n);//分塊的大小爲了讓他排序時按塊排
for(register int i = 1;i <= n;++i)
{
a[i] = gi();
//scanf("%d",&a[i]);
}
q = gi();
//scanf("%d",&q);
int l = 1,r = 0;//最左邊的不相交的
for(register int i = 0;i < q;++i)
{
pp[i].l = gi();
pp[i].r = gi();
//scanf("%d",&pp[i].l);
//scanf("%d",&pp[i].r);
pp[i].step = i;//莫隊的思想記錄第幾個爲了之後輸出
}
sort(pp,pp+q,cmp);
for(register int i = 0;i < q;++i)
{
while(pp[i].l < l)
{
reves(--l,1);//左區間--讓左區間和他相同
}
while(l < pp[i].l)
{
reves(l++,-1);
}
while(pp[i].r < r)
{
reves(r--,-1);
}
while(pp[i].r > r)
{
reves(++r,1);
}
ans[pp[i].step] = res;
}//莫隊
for(register int i = 0;i < q;++i)
{
write(ans[i]);
putchar('\n');
}//輸出答案
return 0;
}