绍兴一中模拟赛10.30——序列

本文介绍了一种解决区间中位数查询问题的算法,针对长度不超过10万的序列和最多5次查询,提供了两种解决方案:一种是O(nmlogn)复杂度的方法,通过标记小于等于目标值的元素进行区间和计算;另一种是O(nm)复杂度的灵活差分方法,提高了查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出一个长度为n(n&lt;=100000)n(n&lt;=100000)n(n<=100000)的序列,有m(m&lt;=5)m(m&lt;=5)m(m<=5)次询问,每次询问有多少个长度∈[l2,r2]∈[l2,r2][l2,r2]的区间,中位数大小∈[l1,r1]∈[l1,r1][l1,r1]

Solution

O(nmlogn)O(nmlogn)O(nmlogn):把&lt;=x&lt;=x<=x的记为111&gt;x&gt;x>x的记为−1-11,计算区间和&gt;=0&gt;=0>=0的区间数
O(nm)O(nm)O(nm):灵活差分

Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=100001;
int a[N],b[N],c[N<<1],n,m,i,l1,r1,l2,r2;
inline char gc(){
	static char buf[100000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int rd(){
	int x=0,fl=1;char ch=gc();
	for (;ch<48||ch>57;ch=gc())if(ch=='-')fl=-1;
	for (;48<=ch&&ch<=57;ch=gc())x=(x<<3)+(x<<1)+(ch^48);
	return x*fl;
}
ll ask(int x,int y){
	memset(c,0,(2*n+1)<<2);
	b[0]=n;
	int s=0;ll ans=0;
	for (int i=1;i<=n;i++){
		if (a[i]<=x) b[i]=b[i-1]+1,s+=c[b[i]];
		else s-=c[b[i-1]],b[i]=b[i-1]-1;
		if (i>=y) c[b[i-y]]++,s+=(b[i]>=b[i-y]);
		ans+=s;
	}
	return ans;
}
int main(){
	n=rd();
	for (i=1;i<=n;i++) a[i]=rd();
	for (m=rd();m--;){
		l1=rd(),r1=rd(),l2=rd(),r2=rd();
		printf("%lld\n",ask(r1,l2)-ask(l1-1,l2)-ask(r1,r2+1)+ask(l1-1,r2+1));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值