基准时间限制:1 秒 空间限制:131072 KB 分值: 40
难度:4级算法题
X轴上有N个点,每个点除了包括一个位置数据X[i],还包括一个权值W[i]。该点到其他点的带权距离 = 实际距离 * 权值。求X轴上一点使它到这N个点的带权距离之和最小,输出这个最小的带权距离之和。
Input
第1行:点的数量N。(2 <= N <= 10000) 第2 - N + 1行:每行2个数,中间用空格分隔,分别是点的位置及权值。(-10^5 <= X[i] <= 10^5,1 <= W[i] <= 10^5)
Output
输出最小的带权距离之和。
Input示例
5 -1 1 -3 1 0 1 7 1 9 1
Output示例
20
把点的权值当作点的数目
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
#define maxn 10005
#define INF 1e15
typedef long long ll;
using namespace std;
struct Node{
friend operator < (const Node&a, const Node&b){
return a.x < b.x;
}
ll x, w;
}node[maxn];
int main(){
// freopen("in.txt", "r", stdin);
int n;
ll sum = 0, x;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%I64d%I64d", &node[i].x, &node[i].w);
sum += node[i].w;
}
sort(node, node+n);
sum = sum % 2 ? sum / 2 + 1: sum / 2;
for(int i = 0; i < n; i++){
sum -= node[i].w;
if(sum <= 0){
x = node[i].x;
break;
}
}
ll ans = 0;
for(int i = 0; i < n; i++){
ans += abs(node[i].x - x) * node[i].w;
}
cout << ans << endl;
return 0;
}