绝对值不等式

题目:货仓选址

link:https://www.acwing.com/problem/content/106/

分析

code

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int arr[N], n;
int main(void) {
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> arr[i];
    sort(arr + 1, arr + n + 1);
    int res = 0;
    for (int i = 1; i <= n; ++i) res += abs(arr[i] - arr[n + 1 >> 1]);         //中位数的求法n + 1除以2,就能得到中位数的序号了
    cout << res << endl;
    return 0;
}

拓展

  • 当变成二维的时候,只要是曼哈顿距离(dist = |y2 - y1|+|x2 - x1|)那么本质就是绝对值不等式,只不过是x,y分别求一下,x跟y互不影响,要是是欧式距离就不能这样了
posted @ 2022-07-28 16:30  SL霸霸  阅读(418)  评论(0编辑  收藏  举报