51nod_距离之和最小 V3(中位数 || 三分)

距离之和最小 V3

Problem Description

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

输出最小的带权距离之和。

Sample Input

5
-1 1
-3 1
0 1
7 1
9 1

Sample Output

20

题解:

正经思路:首先不考虑权值的话,所有数到中位数的距离和是最小的。但是每个数到点的距离都要乘上权值。所以把权值当做点的数量不就行了。(???!)

或者可以考虑三分求目标点。

正经思路的代码:

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctype.h>
#include<cstring>
#include<set>
#include<queue>
#include<stack>
#include<iterator>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define eps 1e-6
 
using namespace std;
typedef long long LL;   
typedef pair<int, int> P;
const int maxn = 50010;
const int mod = 1000000007;
struct node{
    int p, w;
}p[maxn];
bool cmp(node a, node b);

int main()
{
    int n, m, i, j;
    LL ans=0;
    scanf("%d", &n);
    for(i=0;i<n;i++)
        scanf("%d %d", &p[i].p, &p[i].w);
    sort(p, p+n, cmp);
    int l=0, r=n-1;
    while(l<r)
    {
        int mi = min(p[l].w, p[r].w);
        ans += (LL)mi*(p[r].p - p[l].p);
        p[l].w -= mi, p[r].w -= mi;
        if(p[l].w == 0)l++;
        if(p[r].w == 0)r--;
    }
    printf("%lld\n", ans);
    return 0;
}

bool cmp(node a, node b)
{
    return a.p<b.p;
}

三分代码:

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctype.h>
#include<cstring>
#include<set>
#include<queue>
#include<stack>
#include<iterator>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define eps 1e-6
 
using namespace std;
typedef long long LL;   
typedef pair<int, int> P;
const int maxn = 50010;
const int mod = 1000000007;
struct node{
    int p, w;
}p[maxn];
bool cmp(node a, node b);

int main()
{
    int n, m, i, j;
    LL ans=0;
    scanf("%d", &n);
    for(i=0;i<n;i++)
        scanf("%d %d", &p[i].p, &p[i].w);
    sort(p, p+n, cmp);
    int l=0, r=n-1;
    while(l<r)
    {
        int mi = min(p[l].w, p[r].w);
        ans += (LL)mi*(p[r].p - p[l].p);
        p[l].w -= mi, p[r].w -= mi;
        if(p[l].w == 0)l++;
        if(p[r].w == 0)r--;
    }
    printf("%lld\n", ans);
    return 0;
}

bool cmp(node a, node b)
{
    return a.p<b.p;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值