跳到正文

个人记录

P7912 [CSP-J 2021] 小熊的果篮

肖翔约 5 分钟
原文
文章信息与版本

文章信息

发布
2023年7月2日
收录
2026年8月4日
更新
2026年11月11日
篇幅
约 5 分钟
获赞
1

版本

  1. v1当前

(tips:好久以前某次写线段树就想起做这道题,想着用线段树之类的做,这次随机跳到想起来了,圆梦了属于是)

随机跳一不小心又看到当年把我薄纱的题

然而我还是不会链表

set也不会用捏

怎么办怎么办怎么办

考虑题目中的操作,可以转化成轮流取1或0,保证取时保证下标递增,某个位置能取就一定取

容易发现这样转化之后与原题效果一样

我们避开了区间合并,问题转化成如何找出某个位置之后的第一个0或1

这个直接上线段树,树上二分即可

对0,1分别开一棵线段树

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
int tr1[maxn<<2],tr2[maxn<<2];
#define ls(x) ((x)<<1)
#define rs(x) ((x)<<1|1)
inline void pushup(int *tr,int x){
	tr[x]=tr[ls(x)]+tr[rs(x)];
	return;
}
inline void update(int *tr,int x,int l,int r,int pos,int val){
	if(l==r){
		tr[x]=val;
		return;
	}
	int mid=l+r>>1;
	if(pos<=mid)update(tr,ls(x),l,mid,pos,val);
	else update(tr,rs(x),mid+1,r,pos,val);
	pushup(tr,x);
	return;
}
inline int query_sum(int *tr,int x,int l,int r,int nl,int nr){
	if(nl<=l&&r<=nr){
		return tr[x];
	}
	int mid=l+r>>1,ans=0;
	if(nl<=mid)ans+=query_sum(tr,ls(x),l,mid,nl,nr);
	if(mid<nr)ans+=query_sum(tr,rs(x),mid+1,r,nl,nr);
	return ans;
}
inline int query_num(int *tr,int x,int l,int r,int nl,int nr){
	if(l==r)return l;
	int mid=l+r>>1,ans=-1;
	if(nl<=mid&&tr[ls(x)]>0){
		ans=query_num(tr,ls(x),l,mid,nl,nr);
		if(ans!=-1)return ans;
	}
	if(mid<nr&&tr[rs(x)]>0){
		ans=query_num(tr,rs(x),mid+1,r,nl,nr);
		if(ans!=-1)return ans;
	}
	return ans;
}
int n;
int main(){
//	freopen("data.in","r",stdin);
//	freopen("my.out","w",stdout);
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		int x;
		scanf("%d",&x);
		if(x==1)update(tr1,1,1,n,i,1);
		else update(tr2,1,1,n,i,1);
	}
	int now=0,val=1;
	while(query_sum(tr1,1,1,n,1,n)>0&&query_sum(tr2,1,1,n,1,n)>0){
		now=1;
		if(query_num(tr1,1,1,n,now,n)<query_num(tr2,1,1,n,now,n))val=1;
		else val=0;
		while(now<=n){
			if(val==1){
				now=query_num(tr1,1,1,n,now,n);
				if(now==-1)break;
				update(tr1,1,1,n,now,0);
				now++;	
			}
			else {
				now=query_num(tr2,1,1,n,now,n);
				if(now==-1)break;
				update(tr2,1,1,n,now,0);
				now++;
			}
			printf("%d ",now-1);
			val^=1;
		}
		puts("");
	}
	int tmp;
	while(query_sum(tr1,1,1,n,1,n)>0){
		tmp=query_num(tr1,1,1,n,1,n);
		printf("%d\n",tmp);
		update(tr1,1,1,n,tmp,0);
	}
	while(query_sum(tr2,1,1,n,1,n)>0){
		tmp=query_num(tr2,1,1,n,1,n);
		printf("%d\n",tmp);
		update(tr2,1,1,n,tmp,0);
	}
	return 0;
}

注意代码里的val,不一定是从一开始,可能最开始那个要取0,要做判断

把之前补题时我的大常数 O(nn)O(n\sqrt{n}) 链表+懒惰删除做法薄纱

然而被神仙的O(n)O(n)链表薄纱了

不管他,跑了QAQ

原文