Description Wind loves pretty dogs very much, and she has n pet dogs.
So Jiajia has to feed the dogs every day for Wind. Jiajia loves Wind,
but not the dogs, so Jiajia use a special way to feed the dogs. At
lunchtime, the dogs will stand on one line, numbered from 1 to n, the
leftmost one is 1, the second one is 2, and so on. In each feeding,
Jiajia choose an inteval[i,j], select the k-th pretty dog to feed. Of
course Jiajia has his own way of deciding the pretty value of each
dog. It should be noted that Jiajia do not want to feed any position
too much, because it may cause some death of dogs. If so, Wind will be
angry and the aftereffect will be serious. Hence any feeding inteval
will not contain another completely, though the intervals may
intersect with each other.Your task is to help Jiajia calculate which dog ate the food after
each feeding.Input The first line contains n and m, indicates the number of dogs
and the number of feedings.The second line contains n integers, describe the pretty value of each
dog from left to right. You should notice that the dog with lower
pretty value is prettier.Each of following m lines contain three integer i,j,k, it means that
Jiajia feed the k-th pretty dog in this feeding.You can assume that n<100001 and m<50001.
Output Output file has m lines. The i-th line should contain the
pretty value of the dog who got the food in the i-th feeding.
解法一见【这里】。
这里不用树状数组维护,而用线段树维护。这样就不用二分答案,直接计算区间和即可。
时间复杂度变为O(nlogn+mlogn),但是由于常数过大,反而没有解法一快。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct query
{
int l,r,k,num;
bool operator < (const query & qqq) const
{
return l<qqq.l;
}
}q[50010];
int ori[100010],a[100010],ord[100010],m,n,nn,tot=1,lson[600010],rson[600010],s[600010],ans[50010];
void build(int p,int ll,int rr)
{
if (ll==rr) return;
int mid=(ll+rr)/2;
lson[p]=++tot;
build(lson[p],ll,mid);
rson[p]=++tot;
build(rson[p],mid+1,rr);
}
void inc(int p,int ll,int rr,int x)
{
s[p]++;
if (ll==rr) return;
int mid=(ll+rr)/2;
if (x<=mid) inc(lson[p],ll,mid,x);
else inc(rson[p],mid+1,rr,x);
}
void dec(int p,int ll,int rr,int x)
{
s[p]--;
if (ll==rr) return;
int mid=(ll+rr)/2;
if (x<=mid) dec(lson[p],ll,mid,x);
else dec(rson[p],mid+1,rr,x);
}
int find(int p,int ll,int rr,int k)
{
if (ll==rr) return ll;
int l,r,mid,i,j,x;
mid=(ll+rr)/2;
if (s[lson[p]]>=k) return find(lson[p],ll,mid,k);
else return find(rson[p],mid+1,rr,k-s[lson[p]]);
}
int main()
{
int i,j,k,p,x,y,z;
scanf("%d%d",&n,&m);
for (i=1;i<=n;i++)
{
scanf("%d",&ori[i]);
ord[i]=ori[i];
}
sort(ord+1,ord+n+1);
nn=unique(ord+1,ord+n+1)-ord-1;
for (i=1;i<=n;i++)
a[i]=lower_bound(ord+1,ord+nn+1,ori[i])-ord;
for (i=1;i<=m;i++)
{
scanf("%d%d%d",&q[i].l,&q[i].r,&q[i].k);
q[i].num=i;
}
sort(q+1,q+m+1);
q[0].l=q[1].l;
q[0].r=q[1].l-1;
build(1,1,nn);
for (i=1;i<=m;i++)
{
for (j=q[i-1].l;j<q[i].l;j++)
dec(1,1,nn,a[j]);
for (j=q[i-1].r+1;j<=q[i].r;j++)
inc(1,1,nn,a[j]);
ans[q[i].num]=find(1,1,nn,q[i].k);
}
for (i=1;i<=m;i++)
printf("%d\n",ord[ans[i]]);
}