D-query SPOJ - DQUERY(莫队)统计不同数的数量

Posted yewanting

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了D-query SPOJ - DQUERY(莫队)统计不同数的数量相关的知识,希望对你有一定的参考价值。

A - D-query

Given a sequence of n numbers a1, a2, ..., an and a number of d-queries. A d-query is a pair (i, j) (1 ≤ i ≤ j ≤ n). For each d-query (i, j), you have to return the number of distinct elements in the subsequence ai, ai+1, ..., aj.

Input

  • Line 1: n (1 ≤ n ≤ 30000).
  • Line 2: n numbers a1, a2, ..., an (1 ≤ ai ≤ 106).
  • Line 3: q (1 ≤ q ≤ 200000), the number of d-queries.
  • In the next q lines, each line contains 2 numbers i, j representing a d-query (1 ≤ i ≤ j ≤ n).

Output

  • For each d-query (i, j), print the number of distinct elements in the subsequence ai, ai+1, ..., aj in a single line.

     

Example

Input
5
1 1 2 1 3
3
1 5
2 4
3 5

Output
3
2
3 
解题思路:这道题就是给你n个数,q次查询,查询l到r区间有多少个不同的数字;此题用莫队算法;先贴代码,后期补充说明;
代码如下:
 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<algorithm>
 4 #include<cmath>
 5 using namespace std;
 6 
 7 const int maxn = 200005;
 8 int n ;
 9 int m ; 
10 int a[maxn];
11 int ans[maxn];
12 int vis[1000005];
13 int block[maxn]; 
14 int blocksize ;
15 int count1 = 0;
16 struct query{
17     int l ;
18     int r ;
19     int id ;
20 }q[maxn];
21 bool cmp(query a ,query b)
22 {
23     if(block[a.l]==block[b.l])
24         return a.r<b.r;
25     return block[a.l]<block[b.l];
26 }
27 void add(int num)
28 {
29     if(vis[a[num]]==0)
30         count1++;
31     vis[a[num]]++;
32 }
33 void remove(int num){
34     if(vis[a[num]]==1)
35         count1--;
36     vis[a[num]]--;
37 }
38 void solve()
39 {
40     int r = 0;
41     int l = 0;
42     for(int i = 0 ; i < m;i++)
43     {
44         while(q[i].r > r)
45         {
46             r++;
47             add(r);
48         }
49         while(q[i].r<r)
50         {
51             remove(r);
52             r--;
53         }
54         while(q[i].l>l)
55         {
56             remove(l);
57             l++;
58         }
59         while(q[i].l<l)
60         {
61             l--;
62             add(l);
63         }
64         ans[q[i].id] = count1;
65     }
66 }
67 int main()
68 {
69     scanf("%d",&n);
70     blocksize = sqrt(n);
71     for(int i = 1 ; i <= n ; i++)
72     {
73         scanf("%d",&a[i]);
74         block[i] = (i-1)/blocksize + 1;
75     }
76     scanf("%d",&m);
77     for(int i = 0; i < m;i++)
78     {
79         scanf("%d%d",&q[i].l,&q[i].r);
80         q[i].id = i;
81     }
82     sort(q,q+m,cmp);
83     solve();
84     for(int i = 0 ; i < m ;i++ )
85     {
86         printf("%d
",ans[i]);
87     }
88     return 0;
89 }

 

以上是关于D-query SPOJ - DQUERY(莫队)统计不同数的数量的主要内容,如果未能解决你的问题,请参考以下文章

D-query SPOJ - DQUERY(莫队)统计不同数的数量

SPOJ D-query(莫队算法模板)

[SPOJ-DQUERY]D-query

SPOJ3267/DQUERY:D-query——题解

SPOJ DQUERY - D-query

SPOJ DQUERY D-query(主席树)