0
点赞
收藏
分享

微信扫一扫

51nod-1110 距离之和最小 V3(中位数)

您好 2023-06-12 阅读 61


原题链接



1110 距离之和最小 V3



基准时间限制: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 10 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;
}




举报

相关推荐

0 条评论