HDU-5701-中位数计数

来源:互联网 发布:阿里云oss设置http头 编辑:程序博客网 时间:2024/05/20 10:14

Problem Description

中位数定义为所有值从小到大排序后排在正中间的那个数,如果值有偶数个,通常取最中间的两个数值的平均数作为中位数。
现在有n个数,每个数都是独一无二的,求出每个数在多少个包含其的区间中是中位数。

Input
多组测试数据
第一行一个数n(n≤8000)
第二行n个数,0≤每个数≤10^9,

Output
N个数,依次表示第i个数在多少包含其的区间中是中位数。

Sample Input
5
1 2 3 4 5

Sample Output
1 2 3 2 1

Source
2016”百度之星” - 初赛(Astar Round2B)

Recommend
wange2014 | We have carefully selected several similar problems for you: 5717 5716 5715 5714 5713

题解

这里,我们可以分析得到,符合规则的区间有四种形式,分别是:

//      i       (1)//  j---i       (2)//      i---j   (3)//  j'--i--j"   (4)

而这里,第一种不用过多处理,就是1;第2种和第3种类似,所以,我们需要求出来i之前的num的匹配情况,和i之后的num的匹配情况;而第四种要求的是,在第2种和第3种的基础上,进行匹配,匹配成功则符合第4种,这样子,我们把四种情况的结果加在一起也就是答案了。
当然,我们还需要枚举每一个i。

代码(C)

#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAXSIZE 8008int num[MAXSIZE];int arr[MAXSIZE];int cnt[MAXSIZE];int sum[MAXSIZE * 2];//输入intvoid scanfDiy(int *ret){    char c;    *ret = 0;    while((c = getchar()) < '0' || c > '9');    while(c >= '0' && c <= '9')        *ret = (*ret) * 10 + (c - '0'), c = getchar();    return ;}//符合规则的区间分为以下几种//      i       (1)//  j---i       (2)//      i---j   (3)//  j'--i--j"   (4)int main(int argc, const char * argv[]){    int n;    while (~scanf("%d", &n))    {        for (int i = 1; i <= n; i++)        {            scanfDiy(num + i);        }        for (int i = 1; i <= n; i++)        {            int temp = num[i];            memset(arr, 0, sizeof(arr));            memset(sum, 0, sizeof(sum));            int res = 0;            //存num[i]左边区间比num[i]大小情况            for (int j = i - 1; j >= 1; j--)            {                arr[j] = arr[j + 1] + ((num[j] > temp) ? -1 : 1);                sum[arr[j] + n]++;  //防止越界  相同情况出现的次数                if (arr[j] == 0)    //为0时,从j到i区间符合规则                {                    res++;          //(2)                }            }            //存num[i]右边区间比num[i]大小情况            for (int j = i + 1; j <= n; j++)            {                arr[j] = arr[j - 1] + ((num[j] > temp) ? 1 : -1);                if (sum[arr[j] + n] > 0)            //左右匹配                {                    res = res + sum[arr[j] + n];    //(4)                }                if (arr[j] == 0)                    //为0时,从i到j区间符合规则                {                    res++;                          //(3)                }            }            cnt[i] = res + 1;                       //此处+1的情况为(1)        }        for (int i = 1; i < n; i++)        {            printf("%d ", cnt[i]);        }        printf("%d\n", cnt[n]);    }    return 0;}
0 0
原创粉丝点击