日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

D-query SPOJ - DQUERY (主席树)

發布時間:2023/12/20 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 D-query SPOJ - DQUERY (主席树) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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 5Output 3 2 3

?

題意是 給出n個數,m個詢問,每個詢問給出一個區間,需要回答這個區間中不同的數的個數

?

分析:主席樹的經典運用,將主席樹看作擁有n個歷史版本的線段樹, 每個線段樹表示[1,n]的區間,

??????? 節點權值為建造該線段樹為止該區間的貢獻。

??????? 對于構造第i個線段樹,如果a[i]的值已經出現過了, 就將上一 個出現的位置權值-1,再將這次出現的位置權值+1,如果a[i]的值沒有出現,

??????? 則只將這次出現的位置權值+1,也就是說將相同的數產生的貢獻,只記錄在最末尾的為止上,這樣就不會重復。

?????? 這樣對于查詢區間[l,r]首先需要找到第r個線段樹,該樹記錄的是[1,r]中各區間的貢獻。。。

?????? 為了限制起點到l,所以只取該樹中大于等于l的區間的貢獻

?

代碼如下:

#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<algorithm> #include<queue> #include<map> #include<stack> #include<vector> using namespace std; const int MAXN=3e4+10; int a[MAXN]; int vis[1000010]; int root[MAXN]; struct node {int l,r,sum; }T[MAXN*40];int cnt,tmp;void Build(int l,int r,int &x) {int now=++cnt;T[now].sum=0;T[now].l=T[now].r=0;if(l==r)return;int mid=l+r>>1;Build(l,mid,T[now].l);Build(mid+1,r,T[now].r); } void Update(int l,int r,int &x,int y,int pos,int v) {T[++cnt]=T[y],T[cnt].sum+=v,x=cnt;//cout<<T[cnt].sum<<endl;if(l==r)return;int mid=l+r>>1;if(pos<=mid) Update(l,mid,T[x].l,T[y].l,pos,v);else Update(mid+1,r,T[x].r,T[y].r,pos,v); }int query(int pos,int x,int l,int r) {if(l==r)return T[x].sum;int mid=l+r>>1;if(pos<=mid)return T[T[x].r].sum+query(pos,T[x].l,l,mid);else return query(pos,T[x].r,mid+1,r); } int n; int main() {cnt=-1;int n,x,q,l,r;scanf("%d",&n);Build(1,n,root[0]);for(int i=1;i<=n;i++){scanf("%d",&x);if(!vis[x])Update(1,n,root[i],root[i-1],i,1);else{Update(1,n,tmp,root[i-1],vis[x],-1);Update(1,n,root[i],tmp,i,1);}vis[x]=i;}scanf("%d",&q);while(q--){scanf("%d%d",&l,&r);printf("%d\n",query(l,root[r],1,n));}return 0; }

?

轉載于:https://www.cnblogs.com/a249189046/p/8889853.html

總結

以上是生活随笔為你收集整理的D-query SPOJ - DQUERY (主席树)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。