先贴个题目:
以及原题链接:104. 货仓选址 - AcWing题库https://www.acwing.com/problem/content/106/
这题其实很好猜,讲讲我的思路,先来张图:
这是两个商店的情况,x代表仓库选址,绿色x1,红色x2,蓝色x3,不难发现x2的总距离最短。
我们可以吧这个情况推及到2n个商店,只需要取最中间的两个点的中间的任意一点(可包括端点),就能取到距离最小值。
我们接下来讨论下3个商店的情况,如图:
画的有点丑别介意(画了好久,没数位板很痛苦)我再也不想画这个了 。我们可以看到坐落在B点上的仓库(红色)距离最短。由此可以推出2n+1的商店时,仓库选址选在中间那个商店上就好。
结论搞定了,就是代码了:
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int list[N];
int main()
{
int n;
cin >> n;
for (int i = 1; i < n+1;++i)
scanf("%d", &list[i]);
sort(list + 1, list + n + 1);
int ans = list[(n+1) / 2];
ll cnt = 0;
for (int i = 1; i < n + 1;++i)
cnt += abs(list[i] - ans);
cout << cnt;
return 0;
}
by————2024.4.9刷题记录