题意:给定一个含有n个数的数组,每个数的范围都在[1,n]之间,有k个操作,操作有两种,一种是将数组中第k小的数删除,一种向数组中插入一个[1,n]之间的数,在所有操作完成后,如果数组中还有数,那么输出任意一个,否则输出0。
思路:该题乍一看就和一个普通的权值线段树没什么区别,但它给的内存空间比较小,因此线段树区间信息只能作为函数参数传递,而不能写一个结构体来储存区间信息。
代码:
#include <iostream>
#include <windows.h>
using namespace std;
const int N = 1e6+10;
int a[N], sum[N<<2];
void pushUp(int rt)
{
sum[rt] = sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
if(l == r){
sum[rt] = a[l];
return ;
}
int m = (l+r)>>1;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
pushUp(rt);
}
void update(int L,int l,int r,int rt)
{
if(l == r){
sum[rt] += 1;
return ;
}
int m = (l+r)>>1;
if(L <= m) update(L,l,m,rt<<1);
else update(L,m+1,r,rt<<1|1);
pushUp(rt);
}
void update1(int Sum,int l,int r,int rt)
{
if(l == r){
sum[rt] -= 1;
return ;
}
int m = (l+r)>>1;
if(sum[rt<<1] >= Sum) update1(Sum,l,m,rt<<1);
else update1(Sum-sum[rt<<1],m+1,r,rt<<1|1);
pushUp(rt);
}
void query(int l,int r,int rt)
{
if(l == r){
if(sum[rt] > 0){
cout<<l<<'\n';
exit(0);
}
return ;
}
int m = (l+r)>>1;
query(l,m,rt<<1);
query(m+1,r,rt<<1|1);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n, k, t;
cin>>n>>k;
for(int i = 0; i < n; ++i){
cin>>t;
++a[t];
}
build(1,n,1);
while(k--){
cin>>t;
if(t < 0){
t *= -1;
update1(t,1,n,1);
}else{
update(t,1,n,1);
}
}
query(1,n,1);
cout<<0<<'\n';
return 0;
}