题目
题解
写这道题是为了写权值线段树
看到c的范围比较小,按照C为权值建立线段树,c的值就是线段树的叶子位置;
类似于平衡树的做法,查询最左或最有的节点删除
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#define lson (rt<<1)
#define rson (rt<<1|1)
using namespace std;
const int maxn=1e6+10;
const int inf=1e9;
int read(){
char ch=getchar(); int now=0,f=1;
while (ch<'0'||ch>'9') {if (ch=='-') f=-1; ch=getchar();}
while (ch>='0'&&ch<='9') {now=(now<<1)+(now<<3)+ch-'0'; ch=getchar();}
return now*f;}
struct Node{
int w; int c;
}tree[maxn<<2];
void clear(int rt) {tree[rt].w=tree[rt].c=0;}
void pushup(int rt)
{
tree[rt].w=tree[lson].w+tree[rson].w;
tree[rt].c=tree[lson].c+tree[rson].c;
}
void change(int x,int W,int C,int l,int r,int rt)
{
if (l==r)
{
if (tree[rt].c) return;
tree[rt].w=W; tree[rt].c=C; return;
}
int mid=(l+r)>>1;
if (x<=mid) change(x,W,C,l,mid,lson);
else change(x,W,C,mid+1,r,rson);
pushup(rt);
}
void del(int l,int r,int rt,bool flag)//flag标记是否删除最后一个
{
if (l==r) {clear(rt); return;}
int mid=(l+r)>>1;
if (flag && tree[lson].c && tree[rson].c) del(mid+1,r,rson,flag);
else if (!tree[lson].c) del(mid+1,r,rson,flag);
else del(l,mid,lson,flag);
pushup(rt);
}
int main()
{
int opt;
while (opt=read())
{
if (opt==-1) break;
if (opt==1)
{
int w=read(); int c=read();
change(c,w,c,1,maxn,1);
}
if (opt==3) del(1,maxn,1,0);
if (opt==2) del(1,maxn,1,1);
}
printf("%d %d",tree[1].w,tree[1].c);
return 0;
}
总结
善用define