跳到正文

题解

题解:P12570 [UOI 2023] An Array and Medians of Subarrays

Fish_Scale约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年10月24日
收录
2026年10月24日
更新
2026年11月6日
篇幅
约 4 分钟
题目
P12570

版本

  1. v1当前

题目大意

将偶数长度的序列分成偶数个奇长度段使得各段中位数相同。

解析

注意到奇数个连续段可以合并成一个连续段,于是段数为二时最优,考虑枚举断点,将其分成两个奇段,用两个树状数组维护左右段值域和,修改后用两个指针暴力移动即可。

C++
#include<bits/stdc++.h>
#define int long long 
#define LOCAL 0
#define ONLINE 0
using namespace std;
const int N=2e5+10;
int n,a[N];
namespace sl1{
	int _a[N],id[N],ans;
	struct Med{
		int tr[N],n,mid=1;
		int lowb(int x){
			return x&-x;
		}
		inline void update(int x,int k){
			for(x;x<=n;x+=lowb(x))tr[x]+=k;
		}
		inline int query(int x){
			int ans=0;
			for(x;x;x-=lowb(x))ans+=tr[x];
			return ans;
		}
		inline void move(){
			while(mid>1&&query(n)<2*query(mid-1))mid--;
			while(mid<n&&query(n)>2*query(mid))mid++;
		}
		inline void check(){
			for(int i=1;i<=n;i++){
				for(int j=1;j<=query(i)-query(i-1);j++)cout<<i<<' ';
			}
		}
	}cntl,cntr;
	void solve(){
		for(int i=1;i<=n;i++)_a[i]=a[i];
		sort(_a+1,_a+1+n);
		int _n=unique(_a+1,_a+1+n)-_a-1;
		cntl.n =cntr.n =_n;
		for(int i=1;i<=n;i++)id[i]=lower_bound(_a+1,_a+1+_n,a[i])-_a;
	//	for(int i=1;i<=n;i++)cout<<id[i]<<' ';cout<<'\n';
		for(int i=1;i<=n;i++)cntr.update(id[i],1);
//		cntl.check();
//		cntr.check();
		for(int i=1;i<=n;i++){
			cntl.update(id[i],1);
			cntr.update(id[i],-1);
			cntl.move();
			cntr.move();
			if(!(i&1))continue;
//			cout<<"l";cntl.check();
//			cout<<"r";cntr.check();
			
			if(cntl.mid ==cntr.mid ){
				ans=1;
				break;
			}
		}
		if(ans)cout<<"Yes\n";
		else cout<<"No\n";
	}
}
signed main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	#if LOCAL
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
	#endif
	#if ONLINE
	freopen("median.in","r",stdin);
	freopen("median.out","w",stdout);
	#endif
	cin>>n;
	for(int i=1;i<=n;i++)cin>>a[i];
	sl1::solve();
} 
/*
a_min or a_max cant be medium
the stack should be 2k and small than a_med
if f[l,r]=mid cnt_l-1_mid=cnt_r_mid
will the stack more than 2?
if ture there are 4(up) stack
3 stack will be one stack    
only two

*/
原文