题意
给出一条长 米的道路,道路上的坐标范围从 到 ,路上有 座房子,第 座房子建在坐标为 的地方,其中住了 人。
要求在这条路上找一个整数点,求每个居民从家到这个点的距离的总和最短,求这个最小值。
思路
这是一道初一数学题,最小值选择的点一定是 ,所以将题意转化为每个居民从家到 其中的一个点的距离的总和最短。
先将 从小到大排序,方便处理。
设 表示每个居民从家到 这个点的距离总和
推算出公式:
于是我们可以用两个数组一个为 的前缀和,一个为 的前缀和,来解决这个问题。
代码
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e5 + 3;
ll L, n;
struct P{
ll a, b;
}a[N];
ll s1[N], s2[N], ans = 1e18;
int main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> L >> n;
for(int i = 1; i <= n; i ++){
cin >> a[i].a >> a[i].b;
}
sort(a + 1, a + 1 + n, [](const P &x, const P &y) { return x.a < y.a; });
for(int i = 1; i <= n; i ++){
s1[i] = s1[i - 1] + a[i].b;
s2[i] = s2[i - 1] + a[i].a * a[i].b;
}
for(int i = 1; i <= n; i ++){
ans = min(ans, a[i].a * s1[i - 1] - s2[i - 1] + s2[n] - s2[i] - a[i].a * (s1[n] - s1[i]));
}
cout << ans;
return 0;
}