AcWing - 123 - greedy soldiers =

https://www.acwing.com/problem/content/125/

Began to feel very complicated, but in fact, and to the midpoint of the same, but had to wait for x is a sequence, and then let the greedy nearest soldier should go to his position, so as not worse.
So xy is irrelevant, there is always a way so that they will not come to prohibit grid.
Direct sequencing.

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int x[10005], y[10005];

int main() {
#ifdef Yinku
    freopen("Yinku.in", "r", stdin);
#endif // Yinku
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
        scanf("%d%d", &x[i], &y[i]);
    sort(x + 1, x + 1 + n);
    for(int i = 1; i <= n; ++i)
        x[i] -= i;

    sort(x + 1, x + 1 + n);
    sort(y + 1, y + 1 + n);
    int xmid = x[(n + 1) / 2];
    int ymid = y[(n + 1) / 2];
    ll sum = 0;
    for(int i = 1; i <= n; ++i) {
        sum += abs(xmid - x[i]);
        sum += abs(ymid - y[i]);
    }

    printf("%lld\n", sum);
}

Guess you like

Origin www.cnblogs.com/Inko/p/11515937.html