区间内第k小数,求其和。
代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn= 262147;
struct Tree
{
int l,r;
int sum;
}tree[maxn<<2];
inline void PushUp(int rt)
{
tree[rt].sum=tree[rt<<1].sum+tree[rt<<1|1].sum;
}
inline void build(int l,int r,int rt)
{
tree[rt].l=l;
tree[rt].r=r;
if(l==r){
tree[rt].sum=1;
return ;
}
int m=(l+r)>>1;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
PushUp(rt);
}
inline int query(int pos,int rt)
{
int l,r;
l=tree[rt].l;
r=tree[rt].r;
if(l==r){
tree[rt].sum=0;
return l;
}
int m=(l+r)>>1;
int ans;
if(pos<=tree[rt<<1].sum)
ans=query(pos,rt<<1);
else
ans=query(pos-tree[rt<<1].sum,rt<<1|1);
PushUp(rt);
return ans;
}
int main()
{
int T,n,k,ncase=1;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&k);
build(1,n,1);
long long ans=0;
int a;
while(k--){
scanf("%d",&a);
ans+=query(a,1);
}
cout<<"Case "<<ncase++<<": "<<ans<<endl;
}
return 0;
}