HDU 4908 BestCoder Sequence (hash)

来源:互联网 发布:王兆山 真相 知乎 编辑:程序博客网 时间:2024/04/30 19:10

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 115 34 5 3 2 1
 

Sample Output
13
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    }}




0 0