P9176 [COCI2022-2023#4] Vrsta

题意转化

这道题动态的查询当前序列从大到小的序列中的中位数,我们可以浅浅的转化一下,转化成一个求插入值之后求全部序列中的第 K K K 小问题。

那么问题来了,这个 K K K 的值是多少?根据题目所说,如果为单数则直接取最中间数,如果为双数则取中间两数之值中较小的值,所以 K = ⌊ n u m + 1 2 ⌋ K=\lfloor \frac{num+1}{2} \rfloor K=2num+1 其中 n u m num num 为其中当前数列数字个数,所以这就被我们成功的转化成了一个经典的动态第 K K K 小问题,所以整体二分启动。(不会整体二分的可以参考我的博客

代码

#include<bits/stdc++.h>
#define int long long
using namespace std ;
const int N=812345 ;
int n , ans[N] , cnt=0 , now_peoplesum=0 ;
struct node{
	int l , r , opt , k , i ;
}a[N],q1[N],q2[N];
void solve(int l,int r,int L,int R){
	if(L>R) return ;
	if(l==r){
		for(int i=L;i<=R;i++)
			if(a[i].opt==2) ans[a[i].i] = l ;
		return ;
	}
	int mid=(l+r)>>1 , tot1=0 , tot2=0 , sum=0 ;
	for(int i=L;i<=R;i++){
		if(a[i].opt==1){
			if(a[i].l<=mid) sum += a[i].r , q1[++tot1] = a[i] ;
			else q2[++tot2] = a[i] ;
		}else{
			if(a[i].k<=sum)	q1[++tot1] = a[i] ;
			else a[i].k -= sum , q2[++tot2] = a[i] ;
		}
	}
	for(int i=1;i<=tot1;i++) a[i+L-1] = q1[i] ;
	for(int i=1;i<=tot2;i++) a[i+L+tot1-1] = q2[i] ;
	solve(l,mid,L,tot1+L-1) ;
	solve(mid+1,r,tot1+L,R) ;
}
signed main(){
	cin >> n ;
	for(int i=1;i<=n;i++){
		int num , sum ;
		scanf("%lld%lld",&num,&sum) ;
		cnt++ ;
		a[cnt].l = num ;
		a[cnt].r = sum ;
		a[cnt].opt = 1 ;
		now_peoplesum += sum ;
		cnt++ ;
		a[cnt].i = i ;
		a[cnt].k = (now_peoplesum+1)/2 ;
		a[cnt].opt = 2 ;
	}
	solve(-1e9,1e9,1,cnt) ;
	for(int i=1;i<=n;i++)
		printf("%lld\n",ans[i]) ;
	return 0 ;
}

如果你没事干,可以尝试将他离散化,但是可能离散化完,这个代码都跑完了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值