码迷,mamicode.com
首页 > 其他好文 > 详细

SPOJ DQUERY - D-query

时间:2016-09-29 20:59:14      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

DQUERY - 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 
分析:离线树状数组,在线主席树(待写);
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#define rep(i,m,n) for(i=m;i<=n;i++)
#define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define vi vector<int>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define pi acos(-1.0)
#define pii pair<int,int>
#define Lson L, mid, rt<<1
#define Rson mid+1, R, rt<<1|1
const int maxn=1e6+10;
using namespace std;
ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);}
ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;}
inline ll read()
{
    ll x=0;int 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;
}
int n,m,k,t,pos[maxn],a[maxn],b[maxn],ans[maxn];
vector<pii >query[maxn];
void add(int x,int y)
{
    for(int i=x;i<=n;i+=(i&(-i)))
        a[i]+=y;
}
int get(int x)
{
    int ret=0;
    for(int i=x;i;i-=(i&(-i)))
        ret+=a[i];
    return ret;
}
int main()
{
    int i,j;
    scanf("%d",&n);
    rep(i,1,n)scanf("%d",&b[i]);
    scanf("%d",&m);
    rep(i,1,m)
    {
        int c,d;
        scanf("%d%d",&c,&d);
        query[d].pb(mp(c,i));
    }
    rep(i,1,n)
    {
        if(pos[b[i]])add(pos[b[i]],-1);
        pos[b[i]]=i;
        add(pos[b[i]],1);
        for(pii x:query[i])ans[x.se]=get(i)-get(x.fi-1);
    }
    rep(i,1,m)printf("%d\n",ans[i]);
    //system("Pause");
    return 0;
}

SPOJ DQUERY - D-query

标签:

原文地址:http://www.cnblogs.com/dyzll/p/5920839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!