距离之和最小 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;
}