跳到正文

题解

题解:CF74D Hanger

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

文章信息

发布
2026年6月24日
收录
2026年6月24日
更新
2026年11月13日
篇幅
约 5 分钟
题目
CF74D

版本

  1. v1当前

第一眼:什么题这么难?
第二眼:什么题这么简单?

思路

用 set 维护每一个空的区间,用大顶堆维护每个区间的长度和左端点,并且记录每一件的衣服放在哪个位置。

对于加点(放衣服),这个区间一定是堆顶,把它劈成两半,在堆和 set 中暴力修改就行了。

对于删点(拿衣服),找到衣服的位置,在 set 里暴力查找出左右两个空区间,如果说放衣服的位置和这两个区间能拼在一起,就合并。
至于大顶堆,可以延迟删除。在另外一个大顶堆里维护要删的元素,每次如果两个堆堆顶一样,就删掉。

最后要有个树状数组维护区间内挂衣架的情况。

代码
C++
#include <bits/stdc++.h>
using namespace std;
#define debug cerr<<"The code runs successfully.\n";
#define endl '\n'
#define TRACE 1
#define tcout TRACE && cout
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define int long long
#define fir first
#define sec second
const int P = 998244353;
const int Base = 33331;
#ifdef int
const int INF = 0x3f3f3f3f3f3f3f3f;
#else
const int INF = 0x3f3f3f3f;
#endif
const int N = 1e5 + 10, M = 1e6 + 10;
int n,T;
unordered_map<int,int> tr,vis;
priority_queue<pair<int,int>> q,dl;
set<pair<int,int>> st;
inline void add(int x,int k) {//树状数组
	for(;x<=n;x+=x&-x) tr[x]+=k;
}
inline int ask(int x) {
	int res=0;
	for(;x;x-=x&-x) res+=tr[x];
	return res;
}
signed main() {
	fst;
	cin>>n>>T;
	q.push({n,1});
	st.insert({1,n});
	while(T--) {
		int x;
		cin>>x;
		if(x) {
			if(!vis[x]) {//放衣服
				while(!dl.empty()&&q.top()==dl.top()) {//延迟删除
					q.pop(),dl.pop();
				}
				int l=q.top().sec,len=q.top().fir,r=l+len-1,mid=(l+r+1)/2;//mid 是应该放的位置
				q.pop();
				add(mid,1);//修改
				vis[x]=mid;
				auto it=st.lower_bound(pair<int,int>(l,0));
				st.erase(it);
				if(mid-1>=l) {//相当于 ODT 的 split
					st.insert({l,mid-1});
					q.push({(mid-1)-l+1,l});
				}
				if(mid+1<=r) {
					st.insert({mid+1,r});
					q.push({r-(mid+1)+1,mid+1});
				}
			}
			else {//拿衣服
				int pos=vis[x];
				add(pos,-1);//修改
				vis[x]=0;
				int l=pos,r=pos;
				auto it=st.lower_bound(pair<int,int>(pos,0));
				if(it!=st.end()&&it->fir==pos+1) {//左边能拼
					int L=it->fir,R=it->sec;
					r=R;
					st.erase(it);
					dl.push({R-L+1,L});//延迟删
				}
				it=st.lower_bound(pair<int,int>(pos,0));
				if(it!=st.begin()) {
					it--;
					if(it->sec==pos-1) {//右边能拼
						int L=it->fir,R=it->sec;
						l=L;
						st.erase(it);
						dl.push({R-L+1,L});
					}
				}
				st.insert({l,r});//[l,r] 是新区间
				q.push({r-l+1,l});
			}
		}
		else {
			int l,r;
			cin>>l>>r;
			cout<<ask(r)-ask(l-1)<<endl;//询问
		}
	}
	return 0;
}

原文