BZOJ 1303: [CQOI2009]中位数图
题目
Time Limit: 1 Sec Memory Limit: 162 MB
Description
给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b。中位数是指把所有元素从小到大排列后,位于中间的数。
Input
第一行为两个正整数n和b ,第二行为1~n 的排列。
Output
输出一个整数,即中位数为b的连续子序列个数。
Sample Input
7 4
5 7 2 4 3 1 6
Sample Output
4
HINT
第三个样例解释:{4}, {7,2,4}, {5,7,2,4,3}和{5,7,2,4,3,1,6}
N<=100000
题解
首先,我们很容易想到一个暴力,先写一个相比较于数字b的前缀和,再枚举数字b(所在位置为p)左边的i个数字和右边的j个数字,使得sum[p]-sum[i-1]=sum[j]-sum[p-1]
很显然,用上面的这个方法,会超时
然后我就想到了hash,用hash记录下从位置p到位置1相比较于数字b的前缀和的值出现的次数,再枚举从位置p到位置n相比较于数字b的和t,ans:=ans+hash[t];
时间复杂度O(N)
代码(Pascal)
var n,m,ans:longint;
x:array[0..100005]of longint;
hash:array[-100005..100005]of longint;
i,t,p:longint;
begin
//assign(input,'1303.in');reset(input);
//assign(output,'1303.out');rewrite(output);
readln(n,m);t:=0;
for i:=1 to n do
begin
read(x[i]);
if x[i]=m then p:=i;
end;
inc(hash[0]);
for i:=p-1 downto 1 do
begin
if x[i]>m then inc(t) else dec(t);
inc(hash[t]);
end;
t:=0;
for i:=p to n do
begin
if x[i]>m then dec(t) else
if x[i]<m then inc(t);
ans:=ans+hash[t];
end;
write(ans);
//close(input);close(output);
end.

本文介绍了BZOJ1303:[CQOI2009]中位数图的问题,并提供了一种利用哈希解决此问题的方法,通过计算特定位置上数字b的连续子序列的中位数来解决问题。

267

被折叠的 条评论
为什么被折叠?



