P1627 中位数

P1627 中位数

题目描述

给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b。中位数是指把所有元素从小到大排列后,位于中间的数。

输入输出格式

输入格式:

 

第一行为两个正整数n和b,第二行为1~n的排列。

【数据规模】

对于30%的数据中,满足n≤100;

对于60%的数据中,满足n≤1000;

对于100%的数据中,满足n≤100000,1≤b≤n。

 

输出格式:

 

输出一个整数,即中位数为b的连续子序列个数。

 

输入输出样例

输入样例#1:
7 4
5 7 2 4 3 1 6 
输出样例#1:
4

分析

  首先大于b的设为1,小于b的设为-1,p点为b值的坐标。处理L数组和R数组,L[i]表示p左边有多少个点到p的和为i,R[i]表示p右边有多少个点到p的和为i,那么ans=Σ L[i]*R[0-i]。为了没有负数坐标,所以代码中统一加n。

code

 1 #include<cstdio>
 2 
 3 int a[100100];
 4 int l[200100],r[200100],sum[100100];
 5 int read()
 6 {
 7     int x = 0, f = 1; char ch = getchar();
 8     for (; ch<'0'||ch>'9'; ch = getchar())
 9         if (ch=='-') f = -1;
10     for (; ch>='0'&&ch<='9'; ch = getchar())
11         x = x*10+ch-'0';
12     return x*f;
13 }
14 int main()
15 {
16     int n = read(), d = read(), p,ans = 0;
17     for (int x,i=1; i<=n; ++i) {
18         x = read();
19         if (d==x) p = i,a[i] = 0;
20         else if (x<d) a[i] = -1;
21         else a[i] = 1;
22     }
23     l[n] = r[n] = 1;
24     for (int i=p-1; i>=1; --i) {
25         sum[i] = sum[i+1]+a[i];
26         l[sum[i]+n]++;
27     }
28     for (int i=p+1; i<=n; ++i) {
29         sum[i] = sum[i-1]+a[i];
30         r[sum[i]+n]++;
31     }
32     for (int i=0; i<=2*n-1; ++i) ans += l[i]*r[2*n-i];
33     printf("%d",ans);    
34     return 0;
35 }

乱搞70

 1 #include<cstdio>
 2 #include<algorithm>
 3 
 4 
 5 using namespace std;
 6 
 7 int a[10000100];
 8 
 9 int read()
10 {
11     int x = 0, f = 1; char ch = getchar();
12     for (; ch<'0'||ch>'9'; ch = getchar())
13         if (ch=='-') f = -1;
14     for (; ch>='0'&&ch<='9'; ch = getchar())
15         x = x*10+ch-'0';
16     return x*f;
17 }
18 
19 int main()
20 {
21     int n = read(), d = read(), p = -1, xcnt = 0, dcnt = 0,ans = 1;
22     
23     for (int i=1; i<=n; ++i) {
24         a[i] = read();
25         if (d==a[i]) p = i;
26         if (p==-1) {
27             if (a[i]<d) xcnt++;
28             else dcnt++;
29         }
30     }
31     int L = p,da = 0,xo = 0;
32     for (int i=1; ; i+=2) {
33         if (a[--L]>d) da++;else xo++;
34         if (a[--L]>d) da++;else xo++;
35         if (da==xo)    ans++;
36         if (L==1||L==2) break;
37     }
38     
39     for (int i=1; i<=p; ++i) {
40         if (i!=1) {
41             if (a[i-1]>d) dcnt--;
42             else xcnt--;
43         }
44         da = dcnt,xo = xcnt;
45         for (int j=p+1; j<=n; ++j) {
46             if (a[j]>d) da++;else xo++;
47             if (da==xo) ans++;
48         }    
49     }
50     
51     printf("%d",ans);
52         
53     return 0;
54 }
View Code

 

posted @ 2017-09-10 21:09  MJT12044  阅读(296)  评论(0编辑  收藏  举报