HDU 4908 BestCoder Sequence (hash)

BestCoder Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 660    Accepted Submission(s): 231


Problem Description
Mr Potato is a coder.
Mr Potato is the BestCoder.

One night, an amazing sequence appeared in his dream. Length of this sequence is odd, the median number is M, and he named this sequence asBestcoder Sequence.

As the best coder, Mr potato has strong curiosity, he wonder the number of consecutive sub-sequences which arebestcoder sequences in a given permutation of 1 ~ N.
 

Input
Input contains multiple test cases.
For each test case, there is a pair of integers N and M in the first line, and an permutation of 1 ~ N in the second line.

[Technical Specification]
1. 1 <= N <= 40000
2. 1 <= M <= N
 

Output
For each case, you should output the number of consecutive sub-sequences which are theBestcoder Sequences.
 

Sample Input
  
  
1 1 1 5 3 4 5 3 2 1
 

Sample Output
  
  
1 3
Hint
For the second case, {3},{5,3,2},{4,5,3,2,1} are Bestcoder Sequence.
 

Source
BestCoder Round #3


题目链接  :http://acm.hdu.edu.cn/showproblem.php?pid=4908


题目大意  :n个数组成的序列, 给出目标中位数w, 求满足以w为中位数且序列长度为奇数的连续子序列的个数


题目分析  :首先找到中位数m的位置,然后分别向右向左找大于小于中位数的个数,用hash表存储


#include <cstdio>
#include <cstring>
int const MAX  = 40000;
int num[MAX];
int hash[2 * MAX];
int main()
{
    int n, m, left, right, index, ans, mid;
    while(scanf("%d %d", &n, &m) != EOF)
    {
        ans = left = right = 0;
        mid = MAX;
        //每次要对num和hash初始化
        memset(num,0,sizeof(num));
        memset(hash,0,sizeof(hash));
        for(int i = 0; i < n; i++)
            scanf("%d",&num[i]); 
        for(int i = 0; i < n; i++)
        {
            if(num[i] == m)
                index = i;     //找到目标下标
        }
        for(int i = index + 1; i < n; i++)   
        {
            if(num[i] > m)
                right++;   //如果比中位数大则+1,小则-1,以下同
            else
                right--;
            hash[mid+right]++;  
        }
        ans = ++hash[mid];  //目标点值为一属于单独一个集合
        for(int i = index - 1; i >= 0; i--)
        {
            if(num[i] > m)
                left++;
            else
                left--;
            ans += hash[mid-left];   //找到匹配项
        }
        printf("%d\n",ans);
        //第二组样例4 5 3 2 1,按执行顺序:
        //hash[39999] = 1,  hash[39998] = 1;
        //ans += hash[40000] (1);
        //ans += hash[39999] (1);  ans += hash[39998] (1);
        //最后ans值为3
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值