zoukankan      html  css  js  c++  java
  • 货仓选址【中位数】证明

    image

    假设货仓左边所有点到仓库的距离是p, 右边是q, 总距离p+q, 由题可知,要让总距离最小,当仓库向左移动 p – x, 而 但是q会增加n−x,所以说当为仓库中位数的时候,p+qp+q最小。还是同样的一句话,画图理解很重要。

      1 #include <iostream>
      2 #include <algorithm>
      3 using namespace std;
      4 const int N = 1e5 + 5;
      5 int a[N];
      6 int main(){
      7     int n;
      8     cin >> n;
      9     for(int i = 1; i <= n; ++ i)
     10         cin >> a[i];
     11 
     12     sort(a+1, a+1+n);
     13     int pos = 0;
     14     if(n&1) pos = a[(n+1)/2];
     15     else pos = a[n/2 + 1];
     16     int ans = 0;
     17     for(int i = 1; i <= n; ++ i)
     18         ans += abs(a[i] - pos);
     19     cout << ans << endl;
     20     return 0;
     21 }
  • 相关阅读:
    Many Equal Substrings CF
    Seek the Name, Seek the Fame POJ
    人人都是好朋友(离散化 + 并查集)
    建设道路
    day_30
    day_29作业
    day_29
    day_28
    day_27
    day_26作业
  • 原文地址:https://www.cnblogs.com/rstz/p/14391036.html
Copyright © 2011-2022 走看看