CodeForces 166C - Median(思路)

题意:给定 n 个数字,给定一个数 k ,求至少需要添加几个数才能使这 n 个数的中位数等于 k (与数学上的中位数概念不同的是,有 n 个数,下标为 1 ~ n,则中位数为排序后的第 (n + 1) / 2 个数)。

由小到大排序后,先找到最后一个小于 k 的位置,再找到第一个大于 k 的位置,那么中间这些位置都为 k ,看这些位置是否落在中位数的位置上,若没有,则就在这些位置中加 k ,直到满足条件。

 

#include<cstdio>  
#include<cstring>  
#include<cctype>  
#include<cstdlib>  
#include<cmath>  
#include<iostream>  
#include<sstream>  
#include<iterator>  
#include<algorithm>  
#include<string>  
#include<vector>  
#include<set>  
#include<map>  
#include<deque>  
#include<queue>  
#include<stack>  
#include<list>  
typedef long long ll;  
typedef unsigned long long llu;  
const int MAXN = 500 + 10;  
const int MAXT = 10000 + 10;  
const int INF = 0x7f7f7f7f;  
const double pi = acos(-1.0);  
const double EPS = 1e-6;  
using namespace std;  
  
int n, k, a[MAXN];  
  
  
  
int main(){  
    scanf("%d%d", &n, &k);  
    int tmp, ans = 0;  
    for(int i = 0; i < n; ++i)  scanf("%d", a + i);  
    sort(a, a + n);  
    int left = lower_bound(a, a + n, k) - a;  
    int right = upper_bound(a, a + n, k) - a;  
    int mid = (n - 1) / 2;  
    while(mid < left || mid >= right){  
        ++ans;  
        ++right;               //中间加了一个 k 之后,第一个大于 k 的数的下标需要加 1  
        mid = (++n - 1) / 2;   //重新取中位数  
    }  
    printf("%d\n", ans);  
    return 0;  
}  

 

posted @ 2016-10-25 11:16  TianTengtt  阅读(168)  评论(0编辑  收藏  举报