bzoj1878 [SDOI2009]HH的項鍊

Description

HH有一串由各種漂亮的貝殼組成的項鍊。HH相信不同的貝殼會帶來好運,所以每次散步完後,他都會隨意取出一段貝殼,思考它們所表達的含義。HH不斷地收集新的貝殼,因此,他的項鍊變得越來越長。有一天,他突然提出了一個問題:某一段貝殼中,包含了多少種不同的貝殼?這個問題很難回答。。。因爲項鍊實在是太長了。於是,他只好求助睿智的你,來解決這個問題。

Input

第一行:一個整數N,表示項鍊的長度。第二行:N個整數,表示依次表示項鍊中貝殼的編號(編號爲0到1000000之間的整數)。第三行:一個整數M,表示HH詢問的個數。接下來M行:每行兩個整數,L和R(1 ≤ L ≤ R ≤ N),表示詢問的區間。

Output

M行,每行一個整數,依次表示詢問對應的答案。

Sample Input

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

Sample Output

2
2
4

HINT


對於20%的數據,N ≤ 100,M ≤ 1000;
對於40%的數據,N ≤ 3000,M ≤ 200000;
對於100%的數據,N ≤ 50000,M ≤ 200000。


正解:莫隊算法

莫隊板子,巨水。。刷了難一點的就覺得這題沒有任何難度了。。


//It is made by wfj_2048~
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define inf 1<<30
#define il inline
#define RG register
#define ll long long
#define File(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout)

using namespace std;

struct node{ int l,r,i,bl; }q[200010];

int cnt[1000010],ans[200010],a[200010],n,m,block;

il int gi(){
    RG int x=0,q=0; RG char ch=getchar();
    while ((ch<'0' || ch>'9') && ch!='-') ch=getchar(); if (ch=='-') q=1,ch=getchar();
    while (ch>='0' && ch<='9') x=x*10+ch-48,ch=getchar(); return q ? -x : x;
}

il int cmp(const node &a,const node &b){ return a.bl<b.bl || (a.bl==b.bl && a.r<b.r); }

il void work(){
    n=gi(); for (RG int i=1;i<=n;++i) a[i]=gi(); block=sqrt(n); m=gi();
    for (RG int i=1;i<=m;++i) q[i].l=gi(),q[i].r=gi(),q[i].i=i,q[i].bl=(q[i].l-1)/block+1;
    sort(q+1,q+m+1,cmp); RG int L=1,R=0,Ans=0;
    for (RG int i=1;i<=m;++i){
	while (L>q[i].l){ L--,cnt[a[L]]++; if (cnt[a[L]]==1) Ans++; }
	while (R<q[i].r){ R++,cnt[a[R]]++; if (cnt[a[R]]==1) Ans++; }
	while (L<q[i].l){ cnt[a[L]]--; if (!cnt[a[L]]) Ans--; L++; }
	while (R>q[i].r){ cnt[a[R]]--; if (!cnt[a[R]]) Ans--; R--; }
	ans[q[i].i]=Ans;
    }
    for (RG int i=1;i<=m;++i) printf("%d\n",ans[i]); return;
}

int main(){
    File("necklace");
    work();
    return 0;
}


發佈了49 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章