基准时间限制:1 秒 空间限制:131072 KB 分值: 40
难度:4级算法题
X轴上有N个点,每个点除了包括一个位置数据X[i],还包括一个权值W[i]。点P到点P[i]的带权距离 = 实际距离 * P[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 <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
typedef long long LL;
struct node
{
LL x, w;
bool operator <(const node &A)const
{
return x<A.x;
}
}p[N];
int main()
{
int n;
LL sum=0;
scanf("%d", &n);
for(int i=0;i<n;i++)
{
scanf("%lld %lld", &p[i].x,&p[i].w);
sum+=p[i].w;
}
sort(p,p+n);
LL cnt=0, mid=(sum/2)+(sum%2!=0);
int pos;
for(int i=0;i<n;i++)
{
cnt+=p[i].w;
if(cnt>=mid)
{
pos=i;
break;
}
}
LL ans=0;
for(int i=0;i<n;i++)
{
ans+=abs(p[i].x-p[pos].x)*p[i].w;
}
printf("%lld\n",ans);
return 0;
}