Light OJ 1188 Fast Queries(分块暴力)

来源:互联网 发布:北京汉朗网络信息科技 编辑:程序博客网 时间:2024/05/16 09:16

Given an array of N integers indexed from 1 to N, and q queries, each in the form i j, you have to find the number of distinct integers from index i to j(inclusive).

Input

Input starts with an integer T (≤ 5), denoting the number of test cases.

The first line of a case is a blank line. The next line contains two integers N (1 ≤ N ≤ 105)q (1 ≤ q ≤ 50000). The next line contains N space separated integers forming the array. There integers range in [0, 105].

Each of the next q lines will contain a query which is in the form i j (1 ≤ i ≤ j ≤ N).

Output

For each test case, print the case number in a single line. Then for each query you have to print a line containing number of distinct integers from index i to j.

Sample Input

Output for Sample Input

1

 

8 5

1 1 1 2 3 5 1 2

1 8

2 3

3 6

4 5

4 8

Case 1:

4

1

4

2

4

Note


题意:询问区间不同数的个数
分析:注意n<=1e5 所以就直接分块暴力
#include<cstdio>#include<cstring>#include<algorithm>#include<vector>#include<string>#include<iostream>#include<queue>#include<cmath>#include<map>#include<stack>#include<set>using namespace std;#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )#define CLEAR( a , x ) memset ( a , x , sizeof a )const int INF=0x3f3f3f3f;typedef long long LL;const int maxn=1e5+100;int t,n,m;int a[maxn],pos[maxn];int h[maxn];struct node{    int l,r;    int id;}q[maxn];int ans[maxn];int sum;int cmp(node l1,node l2){    if(pos[l1.l]==pos[l2.l])        return l1.r<l2.r;    return pos[l1.l]>pos[l2.l];}void Add(int x){    if(!h[a[x]])        sum++;    h[a[x]]++;}void Sub(int x){    h[a[x]]--;    if(!h[a[x]])        sum--;}int main(){    int x,y;    int cas=1;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        int block=sqrt(n*1.0+0.5);        CLEAR(h,0);        REPF(i,1,n)        {           scanf("%d",&a[i]);           pos[i]=(i-1)/block+1;        }        REP(i,m)        {            scanf("%d%d",&x,&y);            q[i].l=x;q[i].r=y;            q[i].id=i;        }        sort(q,q+m,cmp);        sum=0;int L=1,R=0;        REP(i,m)        {            int l=q[i].l;            int r=q[i].r;            while(R>r) Sub(R--);            while(R<r) Add(++R);            while(L>l) Add(--L);            while(L<l) Sub(L++);            ans[q[i].id]=sum;        }        printf("Case %d:\n",cas++);        for(int i=0;i<m;i++)            printf("%d\n",ans[i]);    }}


0 0
原创粉丝点击