POJ 2104为例
利用归并排序的思想:
#include<cstdio>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;//[)
const int maxn = 1000010;
vector<int>dat[maxn*3];
int sorted[maxn], a[maxn];
void build(int k, int l, int r)
{
if(r - l == 1) dat[k].push_back(a[l]);
else {
int lch = 2 * k + 1, rch = 2 * k + 2;
build(lch, l, (l + r)/2);
build(rch, (l + r)/2, r);
dat[k].resize(r - l);
merge(dat[lch].begin(), dat[lch].end(), dat[rch].begin(), dat[rch].end(),dat[k].begin());
}
}
int query(int l, int r, int x, int k, int L, int R)
{
if(r <= L|| l >= R) return 0;//不相交
else if(l <= L && R <= r){//完全包含
return lower_bound(dat[k].begin(), dat[k].end(), x) - dat[k].begin();
}
else {
int lch = 2 * k + 1, rch = 2 * k + 2;
int lsum = query(l, r, x, lch, L, (L + R)/2);
int rsum = query(l, r, x, rch, (L + R)/2, R);
return lsum + rsum;
}
}
int main (void)
{
int n, m;scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++){
scanf("%d",&a[i]);
sorted[i] = a[i];
}
sort(sorted, sorted+n);
build(0, 0, n);
int tl, tr, k;
while(m--){
scanf("%d%d%d",&tl,&tr,&k);
int l = 0, r = n;
while(r - l >1){
int mid = l + (r - l)/2;
int c = query(tl-1, tr, sorted[mid], 0, 0 ,n);
if(c <= k - 1 ) l = mid;
else r = mid;
}
printf("%d\n", sorted[l]);
}
return 0;
}//6000+ms
#include<cstdio>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;//[)
const int maxn = 1000010;
int dat[20][3*maxn];
int sorted[maxn], a[maxn];
void build(int p, int l, int r)
{
if(r - l == 1) dat[p][l] = a[l];
else {
build(p+1, l, (l + r)/2);
build(p+1, (l + r)/2, r);
merge(dat[p+1] + l, dat[p+1] + (l + r)/2, dat[p+1] + (l + r)/2, dat[p+1] + r, dat[p]+l);
}
}
int query(int l, int r, int x, int p, int L, int R)
{
if(r <= L|| l >= R) return 0;//不相交
else if(l <= L && R <= r){//完全包含
return lower_bound(dat[p]+L, dat[p]+R, x) - (dat[p]+L);
}
else {
int lsum = query(l, r, x, p+1, L, (L + R)/2);
int rsum = query(l, r, x, p+1, (L + R)/2, R);
return lsum + rsum;
}
}
int main (void)
{
int n, m;scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++){
scanf("%d",&a[i]);
sorted[i] = a[i];
}
sort(sorted, sorted+n);
build(0, 0, n);
int tl, tr, k;
while(m--){
scanf("%d%d%d",&tl,&tr,&k);
int l = 0, r = n;
while(r - l >1){
int mid = l + (r - l)/2;
int c = query(tl-1, tr, sorted[mid], 0, 0 ,n);
if(c <= k - 1 ) l = mid;
else r = mid;
}
printf("%d\n", sorted[l]);
}
return 0;
}//2000+ms