51nod1110 距离之和最小 V3

基准时间限制:1 秒 空间限制:131072 KB 分值: 40 
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

 

一个好玩的trick,记一下

 

数学问题 带权中位数

点不带权的话,最优的目标点是点坐标的中位数。(显然)

点带权的话,自然可以想到三分答案或者二分导数,然而这么写多累啊。

注意到点权都是正数,也就是说可以把一个点看成w[i]个相同的点。

现在我们有$ tot = \sum_{i=1}^{n} w[i] $个点。

那么目标点当然就是第$ tot/2 $个点

 

(然而好像优秀的二分/三分写出来比这个短)

 

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 #define LL long long
 7 using namespace std;
 8 const int mxn=100010;
 9 int read(){
10     int x=0,f=1;char ch=getchar();
11     while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();}
12     while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
13     return x*f;
14 }
15 struct node{
16     int x,w;
17     bool operator < (const node &b)const{
18         return x<b.x;
19     }
20 }a[mxn];
21 int n,smm=0;
22 int main(){
23     int i,j;
24     n=read();
25     for(i=1;i<=n;i++){
26         a[i].x=read();
27         a[i].w=read();
28         smm+=a[i].w;
29     }
30     sort(a+1,a+n+1);
31     int mid=0;
32     smm/=2;
33     for(i=1;i<=n;i++){
34         if(a[i].w>=smm){
35             mid=i;
36             break;
37         }
38         smm-=a[i].w;
39     }
40     LL ans=0;
41     for(i=1;i<=n;i++){
42         ans+=abs(a[i].x-a[mid].x)*(LL)a[i].w;
43     }
44     printf("%lld\n",ans);
45     return 0;
46 }

 

posted @ 2017-06-23 17:29  SilverNebula  阅读(150)  评论(0编辑  收藏  举报
AmazingCounters.com