luogu P3031 [USACO11NOV]高于中位数Above the Median (树状数组优化dp)
链接:https://www.luogu.org/problemnew/show/P3031
题面:
题目描述
Farmer John has lined up his N (1 <= N <= 100,000) cows in a row to measure their heights; cow i has height H_i (1 <= H_i <= 1,000,000,000) nanometers--FJ believes in precise measurements! He wants to take a picture of some contiguous subsequence of the cows to submit to a bovine photography contest at the county fair.
The fair has a very strange rule about all submitted photos: a photograph is only valid to submit if it depicts a group of cows whose median height is at least a certain threshold X (1 <= X <= 1,000,000,000).
For purposes of this problem, we define the median of an array A[0...K] to be A[ceiling(K/2)] after A is sorted, where ceiling(K/2) gives K/2 rounded up to the nearest integer (or K/2 itself, it K/2 is an integer to begin with). For example the median of {7, 3, 2, 6} is 6, and the median of {5, 4, 8} is 5.
Please help FJ count the number of different contiguous subsequences of his cows that he could potentially submit to the photography contest.
给出一串数字,问中位数大于等于X的连续子串有几个。(这里如果有偶数个数,定义为偏大的那一个而非中间取平均)
输入输出格式
输入格式:
* Line 1: Two space-separated integers: N and X.
* Lines 2..N+1: Line i+1 contains the single integer H_i.
输出格式:
* Line 1: The number of subsequences of FJ's cows that have median at least X. Note this may not fit into a 32-bit integer.
输入输出样例
说明
FJ's four cows have heights 10, 5, 6, 2. We want to know how many contiguous subsequences have median at least 6.
There are 10 possible contiguous subsequences to consider. Of these, only 7 have median at least 6. They are {10}, {6}, {10, 5}, {5, 6}, {6, 2}, {10, 5, 6}, {10, 5, 6, 2}.
思路:
设dp[i]是从1开始以i结尾的串中大于等于k的有多少个,如果以i结尾以j开始的序列要让中位数大于等于k,那么大于等于k的数的个数就要 > 小于k的数的个数,我们可以得到关系式:
2*(dp[i]-dp[j-1]) >= i-j+1
化简为: 2*dp[i] - i >= 2*dp[j-1] - (j-1) 设 x = 2*dp[i]-i; 注意 -n <= x <= n, 我们把它加上n+1,这样就变成了 1<= x <= 2*n+1, 然后扔到树状数组上就好了,那么当i的x大于j的x,那么区间[j+1,i]这段区间是符合要求的,我们需要在n+1这个点+1,(判断1-i区间是否符合要求)用树状数组统计下从1到当前点有多少个比当前数小的数字,那么就可以得到以i结尾有多少符合题意的序列。
实现代码:
#include<bits/stdc++.h> using namespace std; #define ll long long const int M = 2e5+10; ll c[M],dp[M],n; void add(ll x,ll val){ while(x <= 2*n+1){ c[x] += val; x += (x&-x); } } ll getsum(ll x){ ll ans = 0; while(x){ ans += c[x]; x -= (x&-x); } return ans; } int main() { ll k,x; while(cin>>n>>k){ memset(c,0,sizeof(c)); dp[0] = 0; ll ans = 0; add(n+1,1); for(ll i = 1;i <= n;i ++){ cin>>x; if(x >= k) dp[i] = dp[i-1]+1; else dp[i] = dp[i-1]; ans += getsum(2*dp[i]-i+n+1); add(2*dp[i]-i+n+1,1); } cout<<ans<<endl; } return 0; }