【題解】TIOJ 1732 . 買當勞

【題目敘述】https://tioj.ck.tp.edu.tw/problems/1732
【解題想法】求中位數

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n, a, mid, ans;
vector <int> v;

int main() {
    while (cin >> n){
        v.clear();
        for (int i = 0; i < n; i++){
            cin >> a;
            v.push_back(a);
        }
        sort(v.begin(), v.end());
        ans = 0;
        mid = v[n/2];
        for (int i = 0; i < n; i++){
            ans += abs(v[i]-mid);
        }
        cout << ans << "\n";
    }
}
分享本文 Share with friends