Problem Description Mario is world-famous plumber. His “burly” figure and amazing jumping ability reminded in our memory. Now the poor princess is in trouble again and Mario needs to save his lover. We regard the road to the boss’s castle as a line (the length is n), on every integer point i there is a brick on height hi. Now the question is how many bricks in [L, R] Mario can hit if the maximal height he can jump is H.
Input The first line follows an integer T, the number of test data. For each test data: The first line contains two integers n, m (1 <= n <=10^5, 1 <= m <= 10^5), n is the length of the road, m is the number of queries. Next line contains n integers, the height of each brick, the range is [0, 1000000000]. Next m lines, each line contains three integers L, R,H.( 0 <= L <= R < n 0 <= H <= 1000000000.)
Output For each case, output "Case X: " (X is the case number starting from 1) followed by m lines, each line contains an integer. The ith integer is the number of bricks Mario can hit for the ith query.
Sample Input 1 10 10 0 5 2 7 5 4 3 8 7 7 2 8 6 3 5 0 1 3 1 1 9 4 0 1 0 3 5 5 5 5 1 4 6 3 1 5 7 5 7 3
Sample Output Case 1: 4 0 0 3 1 2 0 1 5 1
Source 2012 ACM/ICPC Asia Regional Hangzhou Online
给出一个长度为n的序列,然后有m次询问,每次询问区间[L,R]之间不大于H的数有多少个
明显主席树,直接上板子,先离散化再建树,对于每次询问,二分找区间[L,R]第k大,判断第k大是否不大于H,如果是就更新答案,在右半段继续二分,如果不是就在左半段找。 复杂度:建树O(NlogN),每次询问O(log2N),总复杂度为O(Nlog2N)
#include<cstdio> #include<cstring> #include<algorithm> #include<vector> using namespace std; const int maxn = 1e5+7; vector<int> vec; int T,n,m,seq[maxn],root[maxn]; struct ljt_Tree{ struct Node{ int l,r,sum; }node[maxn<<5]; int cnt; void init(){ cnt = 0; } void update(int l,int r,int &now,int pre,int pos){ node[++cnt] = node[pre]; node[now=cnt].sum++; if(l+1==r) return; int mid = (l+r)>>1; if(pos<mid) update(l,mid,node[now].l,node[pre].l,pos); else update(mid,r,node[now].r,node[pre].r,pos); } int query(int l,int r,int x,int y,int k){ if(l+1==r) return l; int sum = node[node[y].l].sum-node[node[x].l].sum; int mid = (l+r)>>1; if(sum>=k) return query(l,mid,node[x].l,node[y].l,k); else return query(mid,r,node[x].r,node[y].r,k-sum); } }Seg_Tree; int getid(int x){ return lower_bound(vec.begin(),vec.end(),x)-vec.begin()+1; } bool check(int l,int r,int k,int h){ return vec[Seg_Tree.query(1,n+1,root[l-1],root[r],k)-1]<=h; } int main(){ scanf("%d",&T); for(int kase=1;kase<=T;kase++){ scanf("%d %d",&n,&m); vec.clear(); Seg_Tree.init(); for(int i=1;i<=n;i++) scanf("%d",&seq[i]),vec.push_back(seq[i]); sort(vec.begin(),vec.end()); vec.erase(unique(vec.begin(),vec.end()),vec.end()); for(int i=1;i<=n;i++) Seg_Tree.update(1,n+1,root[i],root[i-1],getid(seq[i])); printf("Case %d:\n",kase); for(int i=1;i<=m;i++){ int l,r,h; scanf("%d %d %d",&l,&r,&h); l++,r++; int tl = 0,tr = r-l+1; int ans = 0; while(tl<=tr){ int mid = (tl+tr)>>1; if(check(l,r,mid,h)){ ans = mid; tl = mid+1; } else tr = mid-1; } printf("%d\n",ans); } } return 0; }