Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Greedy prost
- #define NMAX 2023
- #define ui unsigned int
- #define ll long long
- #define MOD (int)(1e9 + 7)
- #include <bits/stdc++.h>
- using namespace std;
- int N, Max = INT_MIN, Min = INT_MAX;
- vector<int> v;
- ll ans = 0;
- void solve(int mid) {
- int l = mid - 1;
- int r = mid + 1;
- Max = v[mid];
- Min = v[mid];
- while (l >= 0 && r < N)
- {
- int diffLeft = Max - v[l];
- int diffRight = v[r] - Min;
- if (diffLeft < diffRight)
- {
- ans += diffLeft;
- Min = v[l];
- l --;
- }
- else {
- ans += diffRight;
- Max = v[r];
- r ++;
- }
- }
- while (l >= 0){
- ans += (Max - v[l]);
- l--;
- }
- while (r < N) {
- ans += v[r] - Min;
- r ++;
- }
- }
- int main() {
- cin >> N;
- v = vector<int>(N);
- for (int i = 0; i < N; ++i)
- cin >> v[i];
- sort(v.begin(), v.end());
- if (N == 1) {
- cout << 0;
- return 0;
- }
- if (N == 2) {
- return max(v[0], v[1]) - min(v[0], v[1]);
- }
- int mid = N / 2;
- if (N % 2 != 0)
- {
- solve(mid);
- cout << ans << '\n';
- }
- else {
- solve(mid);
- ll sol1 = ans;
- ans = 0;
- solve(mid - 1);
- ll sol2 = ans;
- // cout << sol1 << ' ' << sol2 << '\n';
- cout << min(sol1, sol2);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement