bzoj1878: [SDOI2009]HH的项链(莫队)

www.cnblogs.com/shaokele/


bzoj1878: [SDOI2009]HH的项链##

  Time Limit: 4 Sec
  Memory Limit: 64 MB

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
  

题目地址:  bzoj1878: [SDOI2009]HH的项链

题目大意:   题目很简洁了:)####

  

题解:

  莫队模板题
  
  初写莫队可以先切这题
  
  时间复杂度详见:phoenixgs
  

p1


AC代码

#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int n,m,num,ans;
int a[50005],sum[1000005],Ans[200005];
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
struct node{
    int l,r,op,id;
}A[200005];
bool cmp(node a,node b){
    if(a.op<b.op || (a.op==b.op && a.r<b.r))return 1;
    else return 0;
}
int main(){
    n=read();
    for(int i=1;i<=n;i++)a[i]=read();
    m=read();
     
    num=sqrt(n);
    for(int i=1;i<=m;i++){
        A[i].l=read(),A[i].r=read();
        A[i].op=A[i].l/num;
        A[i].id=i;
    }
    sort(A+1,A+m+1,cmp);
    int L=1,R=0;
    for(int i=1;i<=m;i++){
        while(R<A[i].r)
            if(sum[a[++R]]++==0)ans++;
        while(L>A[i].l)
            if(sum[a[--L]]++==0)ans++;
        while(R>A[i].r)
            if(--sum[a[R--]]==0)ans--;
        while(L<A[i].l)
            if(--sum[a[L++]]==0)ans--;
        Ans[A[i].id]=ans;
    }
    for(int i=1;i<=m;i++)
        printf("%d\n",Ans[i]);
    return 0;
}
posted @ 2018-05-27 20:26  skl_win  阅读(175)  评论(0编辑  收藏  举报
Live2D