zoukankan      html  css  js  c++  java
  • AcWing

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

    一开始觉得很复杂。仔细想想会发现其实排成紧密的一排是和去中点重叠在一起一样的。

    只不过对于x来说要排个序,然后贪心让最近的士兵去他应该去的位置,这样一定是最好的,非常直观,那么他们要移动的距离就可能有正有负,表示他们现在要去到1~n位置自己要移动多少,当然可以把这个队伍作为一个整体一起移动,根据货仓选址问题的启发,要最小化一个作差的绝对值求和式就考虑把差定在中点。

    显然xy是无关的,所以总是存在一种办法使得他们不会走到禁止格。

    直接排序。

    #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
    ", sum);
    }
    
  • 相关阅读:
    poj 1511Invitation Cards
    hust 1608Dating With Girls
    sdibt 2128Problem A:Convolution Codes
    hdu 1325Is It A Tree?
    poj 2240Arbitrage
    hdu 2818Building Block
    poj 1789Truck History
    poj 1125Stockbroker Grapevine
    展望未来
    告别过去
  • 原文地址:https://www.cnblogs.com/Inko/p/11515937.html
Copyright © 2011-2022 走看看