F. Moving Points
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
There are n points on a coordinate axis OX. The i-th point is located at the integer point xi and has a speed vi. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as xi+t⋅vi.
Consider two points i and j. Let d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i,j) will be 0.
Your task is to calculate the value ∑1≤i<j≤n d(i,j) (the sum of minimum distances over all pairs of points).
Input
The first line of the input contains one integer n (2≤n≤2⋅105) — the number of points.
The second line of the input contains n integers x1,x2,…,xn (1≤xi≤108), where xi is the initial coordinate of the i-th point. It is guaranteed that all xi are distinct.
The third line of the input contains n integers v1,v2,…,vn (−108≤vi≤108), where vi is the speed of the i-th point.
Output
Print one integer — the value ∑1≤i<j≤n d(i,j) (the sum of minimum distances over all pairs of points).
Examples
inputCopy
3
1 3 2
-100 2 3
outputCopy
3
inputCopy
5
2 1 4 3 5
2 2 2 3 4
outputCopy
19
inputCopy
2
2 1
-3 0
outputCopy
0
题意: 给你n个点,每个点有一个速度v,对于任意时刻,每个点的位置为x+vt。问对于所有点i,j,∑1≤i<j≤n d(i,j)的最小值是多少。
题解:简单推算可以发现,对于每个位置,我们考虑位置在它左面且速度比他小的或者在它右面速度比他大的,只有这两种情况答案不为0,是我们需要计算的值,又可以发现这两种是同一种情况,即我们考虑以每个位置为右端点,这样只需找出第i个位置左面所有比他速度小的数。将速度离散化后,将位置排序,对于每个位置,ans+=这个位置的x*(比他速度小的点的数量)-(比他速度小的点的x的和)。发现这两个可以用两个树状数组维护。代码清晰
比赛时脑子糊涂了,想到了离散化,先离散化了x发现不对又离散化了s,最后给自己离散的忘了开始怎么想的了。
#include<bits/stdc++.h>
#define int long long
using namespace std ;
#define N 300000
struct node{
int x;int s;
bool operator < (node b){
return x<b.x;
}
}a[1200000];
int ls[1200000];
struct str {
int c[N];
int lowbit(int x) {
return x&(-x);
}
void update(int x,int v) {
for(int i=x; i<=N; i+=lowbit(i))
c[i]+=v;
}
int getsum(int x) {
int res=0;
for(int i=x; i; i-=lowbit(i))
res+=c[i];
return res;
}
int query(int l,int r) {
return getsum(r)-getsum(l-1);
}
} sum,num;
signed main()
{
int n;
cin>>n;
for(int i=0;i<n;i++){
scanf("%lld",&a[i].x);
}
for(int i=0;i<n;i++){
scanf("%lld",&a[i].s);
ls[i]=a[i].s;
}
sort(ls,ls+n);
sort(a,a+n);
for(int i=0;i<n;i++){
a[i].s=lower_bound(ls,ls+n,a[i].s)-ls+1;
}
int ans=0;
for(int i=0;i<n;i++){
ans+=a[i].x*num.getsum(a[i].s)-sum.getsum(a[i].s);
num.update(a[i].s,1);
sum.update(a[i].s,a[i].x);
}
cout<<ans<<endl;
}