跳到正文

题解

P11830 [省选联考 2025] 幸运数字 题解

xixisuper约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟
获赞
1
题目
P11830

版本

仅有当前版本

P11830 [省选联考 2025] 幸运数字 题解

夸一夸出题人的特殊性质,我 3min 会了 B 性质,5min 会了 A 性质,8min 会了正解。

思路

按照考场里的思路来说吧。

性质 B

你发现在这个集合中至多出现 nn 种不同的数,这启发你枚举中位数是哪一个,然后一个一个判断是否可行。

考虑如何判断,有一个很重要的性质:如果想要令 xx 为最终的中位数,则让 xx 出现的次数最多一定不劣。

证明上述性质是很容易的,显然如果 xx 已经是中位数,继续增加 xx 的个数答案不会改变;而如果 xx 不是中位数,则有可能通过增加 xx 的个数的方式使得中位数变成 xx。

此时要想判断 xx 有没有可能成为中位数,只需要知道小于 xx 的数出现的次数范围以及大于 xx 的数出现的次数范围即可。假设小于 xx 的数出现的次数为 [l,r][l,r] 次,大于 xx 的数出现的次数为 [l′,r′][l',r'] 次,则你可以分讨:

  • 如果 [l,r][l,r] 和 [l′,r′][l',r'] 有交,xx 显然可以成为中位数,只需要让小于的个数等于大于的个数即可。
  • 如果 [l,r][l,r] 和 [l′,r′][l',r'] 无交,则需要取相距最近的两个数作为小于的个数和大于的个数,然后判断中位数是否在中间为 xx 的那一部分即可。

于是你做完了性质 B,时间复杂度 O(Tnlog⁡n)O(Tn\log n),瓶颈在于排序。

性质 A

因为限制了集合中出现的数不可能大于 nn,所以你依旧可以枚举中位数是什么。

不过此时会有多个操作覆盖到我们枚举的中位数 xx,怎么统计 xx 出现的次数呢?我们可以考虑把操作排序后丢进优先队列里去维护,边枚举中位数边更新这个优先队列即可。判断一个数是不是中位数的方式和性质 B 中完全一致。

于是你做完了性质 A,时间复杂度 O(Tnlog⁡n)O(Tn\log n),瓶颈在于排序和优先队列。

正解

观察一下性质 A 我们能够发现,如果一段区间内所有的数都被同样的区间所覆盖,那么这段区间内的所有数要么都可以成为中位数,要么都不可以成为中位数。于是我们只需要把枚举中位数变成枚举有多少个不同的区间交即可,这一部分依然可以使用优先队列维护。

最后归到时间复杂度分析,由于总共只有 nn 个区间,所以区间交至多只有 2n2n 个,于是时间复杂度为 O(Tnlog⁡n)O(Tn\log n),瓶颈在于排序和优先队列。

代码

C++
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#define ll long long
using namespace std;
const ll N=2e5+10;
struct node{
	ll numL,numR,cntL,cntR;
	friend bool operator >(const node &a,const node &b){
		return a.numR>b.numR;
	}
}pr[N];
inline bool cmp(node a,node b){
	if(a.numL==b.numL) return a.numR<b.numR;
	return a.numL<b.numL;
}
ll n;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	ll c,T;cin>>c>>T;
	while(T--){
		cin>>n;
		for(ll i=1;i<=n;i++) cin>>pr[i].cntL>>pr[i].cntR>>pr[i].numL>>pr[i].numR;
		sort(pr+1,pr+1+n,cmp);
		priority_queue<node,vector<node>,greater<node> > qu;
		ll premin=0,premax=0,sufmin=0,sufmax=0;
		ll nowcnt=0,top=1;
		for(ll i=1;i<=n;i++){
			sufmin+=pr[i].cntL;
			sufmax+=pr[i].cntR;
		}
		ll L,R,ans=0;
		while(top<=n||!qu.empty()){
			if(qu.empty()){
				L=pr[top].numL;
				sufmin-=pr[top].cntL;
				sufmax-=pr[top].cntR;
				nowcnt+=pr[top].cntR;
				qu.push(pr[top]);
				top++;
			}
			while(top<=n&&L==pr[top].numL){
				sufmin-=pr[top].cntL;
				sufmax-=pr[top].cntR;
				nowcnt+=pr[top].cntR;
				qu.push(pr[top]);
				top++;
			}
			R=(qu.top()).numR;
			if(top<=n) R=min(R,pr[top].numL-1);
			if(premax<sufmin||premin>sufmax){
				ll m;
				if(premax<sufmin){
					m=premax+sufmin+nowcnt;
					m=(m+1)>>1;
					if(m>=premax+1&&m<=premax+nowcnt) ans+=R-L+1;
				}
				else{
					m=premin+sufmax+nowcnt;
					m=(m+1)>>1;
					if(m>=premin+1&&m<=premin+nowcnt) ans+=R-L+1;
				}
			}
			else ans+=R-L+1;
			L=R+1;
			while(!qu.empty()&&(qu.top()).numR<L){
				premin+=(qu.top()).cntL;
				premax+=(qu.top()).cntR;
				nowcnt-=(qu.top()).cntR;
				qu.pop();
			}
		}
		cout<<ans<<"\n";
	}
	return 0;
}
原文