1. 程式人生 > >SPOJ D-query 樹狀陣列離線 求區間內不同數字的個數

SPOJ 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 

1 1 2 1 3 

1 5 
2 4 
3 5

Output 



題意就是查詢區間不同元素的個數,有兩種解法。 
解法1:離線+樹狀陣列,先把詢問離線,並且按照右端點排序,然後從小區間開始,然後樹狀陣列的含義就是指以當前r為結尾的字首區間的元素種類數,簡單點說,就是我當前掃到l , r區間,把l - r區間還沒在樹狀陣列上更新的值,更新一遍,在之前已經存在了的值先刪掉再更新一遍,確保我確定的元素都是往r靠的,這樣才能保證求取區間正確。舉個栗子吧:比如我 1 2 2 1 3,當我r移到3的時候,加入前面的1還沒在樹狀數組裡更新過(但其實之前已經有讀過1了)那就把之前的1的影響刪掉,重新在這個3左邊這個下標為4的位置給樹狀陣列 add 1.這樣確保之後不管我是查詢 4 5 或者 1 5,元素1都只算了一次,但都沒遺落(想想如果元素1一直在下標1那裡,我查詢4 5,就不會有1了)

#include<bits/stdc++.h>
using namespace std;
const int maxn=300010;
const int maxq=1000010;
map<int,int>mp;
struct node
{
    int l,r,id;//輸入查詢的區間
    //id記錄的是每個查詢的次序,目的是在對查詢區間排序後,能按原來的查詢順序輸出結果
};
node q[maxq];
bool cmp(node a,node b)
{
    return a.r<b.r;
}
int c[maxn],n;
int lowbit(int x)
{
    return x&(-x);
}

int sum(int x)
//int query(int x)
{
    int res=0;
    while(x)
    {
        res+=c[x];
        x-=lowbit(x);
    }
    return res;
}
void add(int x,int val)
{
    while(x<=n)
    {
        c[x]+=val;
        x+=lowbit(x);
    }
}
 int a[maxn],ans[maxq];
int main()
{
    int i,j,cur,Q;
    while(~scanf("%d",&n))
    {
        mp.clear();
        memset(c,0,sizeof(c));
        for(i=1;i<=n;i++)
            scanf("%d",&a[i]);
        scanf("%d",&Q);
        for(i=1;i<=Q;i++)
        {
            scanf("%d%d",&q[i].l,&q[i].r);
            q[i].id=i;
        }
        sort(q+1,q+1+Q,cmp);//按右端點排序
        cur=1;
        for(i=1;i<=Q;i++)
        {
            for(j=cur;j<=q[i].r;j++)
            {
                if(mp.find(a[j])!=mp.end())//在前面出現過
                {
                    add(mp[a[j]],-1);
                }
                mp[a[j]]=j;
                add(j,1);
            }
            cur=q[i].r+1;
            ans[q[i].id]=sum(q[i].r)-sum(q[i].l-1);
        }
        //一開始cur=1,是1到q[1].r,先對這個小區間操作,然後cur=q[1].r+1
        //是q[1].r到q[2].r,繼續下去
        for(i=1;i<=Q;i++)
            printf("%d\n",ans[i]);
    }
}