51nod-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 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值