牛客:[CQOI2009]中位数图

牛客:[CQOI2009]中位数图

[CQOI2009]中位数图

题解:
1~n的排列,求连续子序列中位数为k的有多少个?

  1. 首先预处理,大于中位数的表示为1,小于为-1。
  2. 这里用到了前缀和的思想,从中位数向两侧统计,我们很容易知道,左边大于中位数的有多少个,小于中位数的有多少个以及符合条件的有多少个,右边也如此。
  3. 那么在计算右边时,如果右边大于中位数的有m个,那么答案就加上左边小于中位数个数为m的值,这样就可以得出结果了。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>

const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=100005;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

int a[maxn],b[maxn];
map<int,int> mp;
int main()
{
	int n,k,pos=0;
	cin >> n >> k;
	for(int i=0;i<n;i++) 
	{
		cin >> a[i];
		if(a[i]<k) b[i]=-1;
		else if(a[i]>k) b[i]=1;
		else pos=i;
	}
	ll ans=1,sum=0;
	for(int i=pos-1;i>=0;i--)
	{
		sum+=b[i];
		mp[sum]++;
		if(!sum) ans++;
	}
	sum=0;
	for(int i=pos+1;i<n;i++)
	{
		sum+=b[i];
		ans+=mp[-sum];
		if(!sum) ans++;
	}
	cout << ans << endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_44235989/article/details/106661141
今日推荐