Bzoj 1878: [SDOI2009]HH的项链 莫队

1878: [SDOI2009]HH的项链

Time Limit: 4 Sec  Memory Limit: 64 MB
Submit: 2717  Solved: 1363
[Submit][Status][Discuss]

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。

Source

Day2

题解:

直接上莫队即可。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int sum,tot[1000010],ans[200010],color[50010],pos[50010];
 4 struct node
 5 {
 6     int l,r,id;
 7 }q[200010];
 8 int read()
 9 {
10     int s=0,fh=1;char ch=getchar();
11     while(ch<'0'||ch>'9'){if(ch=='-')fh=-1;ch=getchar();}
12     while(ch>='0'&&ch<='9'){s=s*10+(ch-'0');ch=getchar();}
13     return s*fh;
14 }
15 bool cmp(node aa,node bb)
16 {
17     if(pos[aa.l]==pos[bb.l])return aa.r<bb.r;
18     return aa.l<bb.l;
19 }
20 void Del(int C)
21 {
22     tot[C]--;
23     if(tot[C]==0)sum--;
24 }
25 void Add(int C)
26 {
27     tot[C]++;
28     if(tot[C]==1)sum++;
29 }
30 int main()
31 {
32     int n,m,i,block,L,R;
33     n=read();
34     for(i=1;i<=n;i++)color[i]=read();
35     block=(int)sqrt(n);
36     m=read();
37     for(i=1;i<=m;i++)q[i].l=read(),q[i].r=read(),q[i].id=i;
38     for(i=1;i<=n;i++)pos[i]=(int)(i-1)/block+1;
39     sort(q+1,q+m+1,cmp);
40     L=1;R=0;
41     memset(tot,0,sizeof(tot));//每种颜色的数目.
42     for(i=1;i<=m;i++)
43     {
44         while(L<q[i].l)
45         {
46             Del(color[L]);
47             L++;
48         }
49         while(L>q[i].l)
50         {
51             L--;
52             Add(color[L]);
53         }
54         while(R<q[i].r)
55         {
56             R++;
57             Add(color[R]);
58         }
59         while(R>q[i].r)
60         {
61             Del(color[R]);
62             R--;
63         }
64         ans[q[i].id]=sum;
65     }
66     for(i=1;i<=m;i++)printf("%d\n",ans[i]);
67     fclose(stdin);
68     fclose(stdout);
69     return 0;
70 }
View Code

 

posted @ 2016-03-21 10:34  微弱的世界  阅读(385)  评论(0编辑  收藏  举报