BZOJ 1303: [CQOI2009]中位数图

4 篇文章 0 订阅

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.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值