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 as Bestcoder Sequence.
As the best coder, Mr potato has strong curiosity, he wonder the number of consecutive sub-sequences which are bestcoder 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 the Bestcoder 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.
题目链接:HDU-4908
题目大意:给出1~n的无序序列。求中位数为m的子序列有多少种情况
题目思路:找到中位数,然后向前遍历,遇到>m的数字k++,<m的数字则k–,存储每个k到mp1中,同理向后遍历,存到mp2中。
然后遍历mp1数组里所有的值k,找到对应mp2数组里面的-k,相乘。
以下是代码:
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
int num[40010];
int ret[40010];
map <int,int> mp1,mp2;
int main(){
int n,m;
while(scanf("%d%d",&n,&m)!= EOF)
{
mp1.clear();
mp2.clear();
memset(num,0,sizeof(num));
memset(ret,0,sizeof(ret));
int poi = -1;
for (int i = 0; i < n; i++)
{
cin >> num[i];
if (num[i] > m) ret[i] = 1;
else if (num[i] == m) ret[i] = 0,poi = i;
else ret[i] = -1;
}
int ans = 0;
mp1[0] = 1; //注意
mp2[0] = 1;
int i = poi;
int k = 0;
for (int j = i - 1; j >= 0; j--)
{
k += ret[j];
mp1[k]++;
}
k = 0;
for (int j = i + 1; j < n; j++)
{
k += ret[j];
mp2[k]++;
}
map<int,int>::iterator ite;
for(ite = mp1.begin();ite != mp1.end();ite++)
{
int temp = (*ite).first * (-1);
if (mp2.count(temp) != 0)
{
ans += (*ite).second * mp2[temp];
}
}
printf("%d\n",ans);
}
return 0;
}