【Manthan, Codefest 18 (rated, Div. 1 + Div. 2) B】Reach Median

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

将数组排序一下。 考虑中位数a[mid] 如果a[mid]==s直接输出0 如果a[mid]s,那么我们把a[mid]还是改成s,然后把1..mid-1这里面比s大的都改成s.这样就能满足要求了。(mid+1..n这一部分都是 大于a[mid]的不用动) (同理也不会改a[mid+1..n]的,因为改动的花费更多

【代码】

#include <bits/stdc++.h>
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define all(x) x.begin(),x.end()
#define pb push_back
#define lson l,mid,rt<<1
#define ri(x) scanf("%d",&x)
#define rl(x) scanf("%lld",&x)
#define rs(x) scanf("%s",x)
#define rson mid+1,r,rt<<1|1
using namespace std;

const double pi = acos(-1);
const int dx[4] = {0,0,1,-1};
const int dy[4] = {1,-1,0,0};
const int N = 2e5;

int n,s,cnt1,cnt2;
int a[N+10];
vector<int> v[2];

int main(){
	#ifdef LOCAL_DEFINE
	    freopen("rush_in.txt", "r", stdin);
	#endif
	scanf("%d%d",&n,&s);
	rep1(i,1,n) scanf("%d",&a[i]);
	sort(a+1,a+1+n);
    int key = n/2;
    key++;
    if (a[key]==s){
        puts("0");
    }else{
        long long ans = 0;
        if (a[key]<s){
            rep1(i,key,n){
                if (a[i]<s){
                    ans += s-a[i];
                }
            }
        }else{
            //a[key]>s
            rep2(i,key,1){
                if (a[i]>s){
                    ans += a[i]-s;
                }
            }
        }
        printf("%lld
",ans);
    }
	return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/9576636.html