1303: [CQOI2009]中位数图
Time Limit: 1 Sec Memory Limit: 162 MB[Submit][Status][Discuss]
Description
给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b。中位数是指把所有元素从小到大排列后,位于中间的数。
Input
第一行为两个正整数n和b ,第二行为1~n 的排列。
Output
输出一个整数,即中位数为b的连续子序列个数。
Sample Input
7 4
5 7 2 4 3 1 6
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
Source
因为是n的排列,b只会出现一次,b记为0,比b小记为-1,比b大记为1,所求为和为0的序列个数
然后从值为b的点向前向后分别统计一下前缀和,互为相反数的组数就是答案
C++数组下标不能是负的感觉这题写Pascal更方便一点QAQ
1 var 2 n, k, x, q, ans, i: longint; 3 a : array [1 .. 1010000] of integer; 4 s : array [-1010000 .. 1010000] of longint; 5 begin 6 readln(n, k); 7 for i := 1 to n do 8 begin 9 read(x); 10 if (x = k) 11 then begin 12 a[i] := 0; 13 q := i; 14 end 15 else begin 16 if (x > k) then a[i] := 1 else a[i] := -1; 17 end; 18 end; 19 x := 0; 20 ans := 1; 21 for i := q - 1 downto 1 do 22 begin 23 x := x + a[i]; 24 s[x] := s[x] + 1; 25 if (x = 0) then ans := ans + 1; 26 end; 27 x := 0; 28 for i := q + 1 to n do 29 begin 30 x := x + a[i]; 31 ans := ans + s[-x]; 32 if (x = 0) then ans := ans + 1; 33 end; 34 writeln(ans); 35 end. 36