P11830 [省选联考 2025] 幸运数字 题解
P11830 [省选联考 2025] 幸运数字 题解
夸一夸出题人的特殊性质,我 3min 会了 B 性质,5min 会了 A 性质,8min 会了正解。
思路
按照考场里的思路来说吧。
性质 B
你发现在这个集合中至多出现
考虑如何判断,有一个很重要的性质:如果想要令
证明上述性质是很容易的,显然如果
此时要想判断
- 如果
[l,r] 和[l',r'] 有交,x 显然可以成为中位数,只需要让小于的个数等于大于的个数即可。 - 如果
[l,r] 和[l',r'] 无交,则需要取相距最近的两个数作为小于的个数和大于的个数,然后判断中位数是否在中间为x 的那一部分即可。
于是你做完了性质 B,时间复杂度
性质 A
因为限制了集合中出现的数不可能大于
不过此时会有多个操作覆盖到我们枚举的中位数
于是你做完了性质 A,时间复杂度
正解
观察一下性质 A 我们能够发现,如果一段区间内所有的数都被同样的区间所覆盖,那么这段区间内的所有数要么都可以成为中位数,要么都不可以成为中位数。于是我们只需要把枚举中位数变成枚举有多少个不同的区间交即可,这一部分依然可以使用优先队列维护。
最后归到时间复杂度分析,由于总共只有
代码
#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;
}