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.
【题目分析】
区间不覆盖的区间第K大问题,只需要维护两个指针l,r,然后把区间离线,然后排序。之后呢,只需要每次把离散化后的a[r+1]加入,然后把a[l]弹出去,就可以nlogn的查询了。
树状数组写起来还是很方便的。神奇的lowbit
【代码】
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int a[100001],lsa[100001];
int rank[50001],l[50001],r[50001],k[50001];
int t[100001];
int out[50001];
int ls[100001],ys[100001];
int n,m;
inline int lowbit(int x)
{return x&(-x);}
inline bool cmp(int a,int b)
{return l[a]<l[b];}
inline void add(int x,int opt)
{for (;x<=n;x+=lowbit(x))t[x]+=opt;}
inline int getsum(int x)
{int ret=0;for (;x>=1;x-=lowbit(x))ret+=t[x];return ret;}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;++i) scanf("%d",&a[i]);
for (int i=1;i<=m;++i) scanf("%d%d%d",&l[i],&r[i],&k[i]);
for (int i=1;i<=m;++i) rank[i]=i;
sort(rank+1,rank+m+1,cmp);
int pl=1,pr=0;
memcpy(ls,a,sizeof a);int top=n;
sort(ls+1,ls+top+1);
top=unique(ls+1,ls+top+1)-ls-1;
for (int i=1;i<=n;++i) lsa[i]=lower_bound(ls+1,ls+top+1,a[i])-ls,ys[lsa[i]]=a[i];
// for (int i=1;i<=n;++i) cout<<lsa[i]<<" ";cout<<endl;
for (int i=1;i<=m;++i)
{
int nowl=l[rank[i]],nowr=r[rank[i]];
for (int j=pr+1;j<=nowr;++j) add(lsa[j],1);
for (int j=pl;j<nowl;++j) add(lsa[j],-1);
int ll=1,rr=n;
while (ll<rr)
{
int mid=(ll+rr)/2;
int ans=getsum(mid);
if (ans>=k[rank[i]]) rr=mid;
else ll=mid+1;
}
out[rank[i]]=ll;
// cout<<ll<<endl;
pl=nowl;pr=nowr;
}
for (int i=1;i<=m;++i) cout<<ys[out[i]]<<endl;
}