Codeforces 1037B Reach Median (STL,二分)

题目链接

http://codeforces.com/contest/1037/problem/B

题意

给定n和s。然后有n个数。
对第i个数可以进行操作,将其值加1或者减1。
求使得n个的中位数为s的最少操作次数。
中位数的意思就是将n个数排序后恰好在第n/2+1位的数。n保证是奇数。

题解

首先将n个数进行排序。
然后找出值为s的数的起始位置l和最终位置r。

如果l在中间位置mid的右边,那么将l左边连续l-mid个数的值都操作加到s即可。

如果r在中间位置mid的左边,那么将r右边连续mid-r个数的值都减到s即可。

AC代码

#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+7;

int a[maxn];

int main()
{
    int n,s;
    while(~scanf("%d%d",&n,&s))
    {
        int x=n/2+1;
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        int l=lower_bound(a,a+n,s)-a;
        int r=upper_bound(a,a+n,s)-a-1;
        long long ans=0;
        //cout<<a[l]<<" "<<a[r]<<"  "<<l<<" "<<r<<endl;
        if(l+1>x)
        {
            int c=l+1-x,t=l-1;
            //cout<<"c="<<c<<endl;
            while(c--)
            {
                ans+=(long long)(s-a[t]);
                t--;
            }
        }
        else if(r+1<x)
        {
            int c=x-(r+1),t=r+1;
            while(c--)
            {
                ans+=(long long)(a[t]-s);
                t++;
            }
        }
        printf("%I64d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37685156/article/details/82351596