Search is not available for this dataset
name
stringlengths 2
88
| description
stringlengths 31
8.62k
| public_tests
dict | private_tests
dict | solution_type
stringclasses 2
values | programming_language
stringclasses 5
values | solution
stringlengths 1
983k
|
|---|---|---|---|---|---|---|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
/**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class ACMIND
{
static FastReader scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 2_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<27)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n;
static Integer[] map;
static long BIT[], BIT_count[];
static void solve() throws IOException
{
scan = new FastReader();
pw = new PrintWriter(System.out,true);
StringBuilder sb = new StringBuilder();
n = ni();
int x[] = new int[n];
for(int i=0;i<n;++i) {
x[i] = ni();
}
compress1(x, n);
Pair arr[] = new Pair[n];
for(int i=0;i<n;++i) {
arr[i] = new Pair(ni(), x[i]);
}
Arrays.sort(arr);
BIT = new long[n+1];
BIT_count = new long[n+1];
long ans = 0;
for(int i=n-1;i>=0;--i) {
long total[] = query(n);
long less_equal[] = query(arr[i].y);
long resultant[] = new long[]{total[0] - less_equal[0], total[1] - less_equal[1]};
ans+=resultant[0] - resultant[1] * map[arr[i].y];
update(arr[i].y, map[arr[i].y]);
}
pl(ans);
pw.flush();
pw.close();
}
static void update(int index,long val)
{
for(int i=index;i<=n;i+=i&-i)
{
BIT[i]+=val;
BIT_count[i]++;
}
}
static long[] query(int index)
{
long res[] = new long[2];
for(int i=index;i>0;i-=i&-i) {
res[0]+=BIT[i];
res[1]+=BIT_count[i];
}
return res;
}
static void compress1(int arr[],int n)
{
map = new Integer[n+1];
for(int i=0;i<n;++i)
map[i+1] = arr[i];
map[0] = Integer.MIN_VALUE;
Arrays.sort(map);
int low,high,mid;
for(int i=0;i<n;++i)
{
low = 1;
high = n;
while(low<high)
{
mid = (low+high)>>1;
if(map[mid]==arr[i])
{
low = mid;
break;
}
if(map[mid]>arr[i])
high = --mid;
else low = ++mid;
}
arr[i] = low;
}
}
static class Pair implements Comparable<Pair>
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(Pair other)
{
if(this.x!=other.x)
return this.x-other.x;
return this.y-other.y;
}
public String toString()
{
return "("+x+","+y+")";
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1000000];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e6 + 100, mod = 1e9 + 7, inf = 1e16 + 7;
pair<long long, long long> a[maxn];
long long get(long long l, long long r) {
if (r - l == 1) return 0;
long long m = (r + l) / 2;
long long ans = 0;
ans += get(l, m);
ans += get(m, r);
long long ptr = m;
vector<long long> pref(r - m + 2, 0);
for (long long i = r - 1; i >= m; --i) {
pref[i - m] = pref[i + 1 - m] + a[i].first;
}
vector<pair<long long, long long> > tmp;
for (long long i = l; i < m; ++i) {
while (ptr < r && a[i].second > a[ptr].second) {
tmp.push_back(a[ptr]);
ptr++;
}
tmp.push_back(a[i]);
ans += pref[ptr - m];
ans -= (r - ptr) * a[i].first;
}
while (ptr < r) tmp.push_back(a[ptr]), ptr++;
for (long long i = l; i < r; ++i) {
a[i] = tmp[i - l];
}
return ans;
}
void solve() {
long long n;
cin >> n;
for (long long i = 0; i < n; ++i) {
cin >> a[i].first;
}
for (long long i = 0; i < n; ++i) {
cin >> a[i].second;
}
sort(a, a + n);
cout << get(0, n);
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
srand(10);
cout << fixed << setprecision(2);
long long t = 1;
while (t--) {
solve();
cout << endl;
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = (int)2e5 + 100;
const int mod = (int)1e9 + 7;
int n, c[maxn];
long long ans;
pair<int, int> a[maxn];
int main() {
scanf("%d", &n);
for (auto i = (1); i <= (n); ++i)
scanf("%d", &a[i].second), c[i] = a[i].second;
for (auto i = (1); i <= (n); ++i) scanf("%d", &a[i].first);
sort(a + 1, a + 1 + n);
sort(c + 1, c + 1 + n);
for (auto i = (1); i <= (n); ++i)
ans += (i - 1 - n + lower_bound(c + 1, c + 1 + n, a[i].second) - c) *
(long long)a[i].second;
printf("%lld\n", ans);
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int b[200005], m;
long long tr[800005][2];
struct node {
int x, v;
bool operator<(const node t) const { return x < t.x; }
} a[200005];
int lsh(long long x) { return lower_bound(b + 1, b + 1 + m, x) - b; }
long long query(int l, int r, int x, int y, int z, int p) {
if (l == x && r == y) return tr[p][z];
int mid = l + r >> 1;
if (y <= mid)
return query(l, mid, x, y, z, p << 1);
else if (x > mid)
return query(mid + 1, r, x, y, z, p << 1 | 1);
else
return query(l, mid, x, mid, z, p << 1) +
query(mid + 1, r, mid + 1, y, z, p << 1 | 1);
}
void update(int l, int r, int x, int y, int p) {
if (l == r) {
tr[p][0]++;
tr[p][1] += y;
return;
}
int mid = l + r >> 1;
if (x <= mid)
update(l, mid, x, y, p << 1);
else
update(mid + 1, r, x, y, p << 1 | 1);
tr[p][0] = tr[p << 1][0] + tr[p << 1 | 1][0];
tr[p][1] = tr[p << 1][1] + tr[p << 1 | 1][1];
}
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i].x);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i].v);
b[i] = a[i].v;
}
sort(b + 1, b + 1 + n);
m = unique(b + 1, b + 1 + n) - b - 1;
sort(a + 1, a + 1 + n);
long long ans = 0;
for (int i = 1; i <= n; i++) {
int x = lsh(a[i].v);
ans += query(1, m, 1, x, 0, 1) * a[i].x - query(1, m, 1, x, 1, 1);
update(1, m, x, a[i].x, 1);
}
printf("%lld", ans);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
const int inf = 0x3f3f3f3f;
const long long INF = 0x7f7f7f7f7f7f7f7f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps = 1e-5;
int n;
pair<long long, long long> a[maxn];
long long b[maxn];
long long s1[maxn], s2[maxn];
int lb(int x) { return x & (-x); }
void add(int x, long long w) {
for (int i = x; i <= n; i += lb(i)) {
s1[i]++;
s2[i] += w;
}
}
long long sum1(int x) {
long long res = 0;
for (int i = x; i >= 1; i -= lb(i)) res += s1[i];
return res;
}
long long sum2(int x) {
long long res = 0;
for (int i = x; i >= 1; i -= lb(i)) res += s2[i];
return res;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i].first);
}
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i].second);
b[i] = a[i].second;
}
sort(a + 1, a + 1 + n);
sort(b + 1, b + 1 + n);
int len = unique(b + 1, b + 1 + n) - (b + 1);
long long ans = 0;
for (int i = 1; i <= n; i++) {
int pos = lower_bound(b + 1, b + 1 + len, a[i].second) - b;
long long res1 = sum1(pos);
long long res2 = sum2(pos);
ans += res1 * a[i].first - res2;
add(pos, a[i].first);
}
printf("%lld", ans);
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long INF = 4e18 + 10;
long long power(long long a, long long b, long long in_mod) {
long long ans = 1;
long long prod = a;
while (b) {
if (b % 2) ans = (ans * prod) % in_mod;
prod = (prod * prod) % in_mod;
b /= 2;
}
return ans;
}
long long mod_inv(long long q, long long in_mod) {
return power(q, in_mod - 2, in_mod);
}
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
long long fact(long long n, long long in_mod) {
long long f = 1;
for (long long i = 1; i <= n; i++) f = (f * i) % in_mod;
return f;
}
long long ncr(long long n, long long r, long long in_mod) {
return (((fact(n, in_mod) * mod_inv(fact(r, in_mod), in_mod)) % in_mod) *
mod_inv(fact(n - r, in_mod), in_mod)) %
in_mod;
}
long long A[200005] = {};
long long tree[4 * 200005] = {};
long long cnt[4 * 200005] = {};
void update(long long node, long long start, long long end, long long idx,
long long val) {
if (start == end) {
A[idx] += val;
tree[node] += val;
cnt[node] += 1;
} else {
long long mid = (start + end) / 2;
if (start <= idx and idx <= mid) {
update(2 * node, start, mid, idx, val);
} else {
update(2 * node + 1, mid + 1, end, idx, val);
}
tree[node] = tree[2 * node] + tree[2 * node + 1];
cnt[node] = cnt[2 * node] + cnt[2 * node + 1];
}
}
long long query1(long long node, long long start, long long end, long long l,
long long r) {
if (r < start or end < l) {
return 0;
}
if (l <= start and end <= r) {
return tree[node];
}
long long mid = (start + end) / 2;
long long p1 = query1(2 * node, start, mid, l, r);
long long p2 = query1(2 * node + 1, mid + 1, end, l, r);
return (p1 + p2);
}
long long query2(long long node, long long start, long long end, long long l,
long long r) {
if (r < start or end < l) {
return 0;
}
if (l <= start and end <= r) {
return cnt[node];
}
long long mid = (start + end) / 2;
long long p1 = query2(2 * node, start, mid, l, r);
long long p2 = query2(2 * node + 1, mid + 1, end, l, r);
return (p1 + p2);
}
void solve() {
long long n;
cin >> n;
map<long long, long long> mp;
vector<long long> dis(n);
vector<pair<long long, long long> > v(n);
for (long long i = 0; i < n; i++) {
cin >> v[i].second;
dis[i] = v[i].second;
}
for (long long i = 0; i < n; i++) cin >> v[i].first;
sort((v).begin(), (v).end());
sort((dis).begin(), (dis).end());
for (long long i = 0; i < n; i++) mp[dis[i]] = i;
update(1, 0, 200005 - 1, mp[v[0].second], v[0].second);
long long ans = 0;
for (long long i = 1; i < n; i++) {
long long _sum = query1(1, 0, 200005 - 1, 0, mp[v[i].second]);
long long _cnt = query2(1, 0, 200005 - 1, 0, mp[v[i].second]);
ans += _cnt * (v[i].second) - _sum;
update(1, 0, 200005 - 1, mp[v[i].second], v[i].second);
}
cout << ans << '\n';
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cout << fixed << setprecision(10);
auto clk = clock();
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
long long t = 1;
for (long long test = 1; test <= t; test++) {
solve();
}
clk = clock() - clk;
cerr << fixed << setprecision(6)
<< "Time: " << ((long double)clk) / CLOCKS_PER_SEC << "\n";
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int Z = (int)1e3 + 228;
const int N = (int)2e5 + 228;
const int INF = (int)1e9 + 228;
const int MOD = (int)998244353;
const long long LLINF = (long long)1e18 + 228;
const long double eps = (long double)1e-6;
pair<long long, long long> t[4 * N];
void update(int v, int tl, int tr, int pos, int x) {
if (tl == tr) {
t[v].first += x;
t[v].second++;
return;
}
int mid = (tl + tr) / 2;
if (pos <= mid)
update(2 * v, tl, mid, pos, x);
else
update(2 * v + 1, mid + 1, tr, pos, x);
t[v].first = t[2 * v].first + t[2 * v + 1].first;
t[v].second = t[2 * v].second + t[2 * v + 1].second;
}
pair<long long, long long> get_sum(int v, int tl, int tr, int l, int r) {
if (tl >= l && tr <= r) {
return t[v];
}
if (tl > r || tr < l) {
return {0, 0};
}
int mid = (tl + tr) / 2;
pair<long long, long long> ql = get_sum(2 * v, tl, mid, l, r);
pair<long long, long long> qr = get_sum(2 * v + 1, mid + 1, tr, l, r);
return {ql.first + qr.first, ql.second + qr.second};
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<pair<int, int> > a(n);
for (int i = 0; i < n; i++) {
cin >> a[i].first;
}
vector<int> v;
for (int i = 0; i < n; i++) {
cin >> a[i].second;
v.push_back(a[i].second);
}
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
sort(a.begin(), a.end());
long long ans = 0;
for (int i = 0; i < n; i++) {
int pos = lower_bound(v.begin(), v.end(), a[i].second) - v.begin();
pair<long long, long long> p = get_sum(1, 0, v.size() - 1, 0, pos);
ans += p.second * a[i].first - p.first;
update(1, 0, v.size() - 1, pos, a[i].first);
}
cout << ans;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.util.Arrays;
import java.util.Scanner;
import java.util.Comparator;
public class R624_F {
private static long sum (long[] t, int pos) {
long result = 0;
while (pos >= 0) {
result += t[pos];
pos = (pos & (pos + 1)) - 1;
}
return result;
}
private static void upd (long[] t, int pos, int delta) {
while (pos < t.length) {
t[pos] += delta;
pos = pos | (pos + 1);
}
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int n = in.nextInt();
int[][] p = new int[n][2];
Integer[] v = new Integer[n];
for (int i = 0; i < n; i++)
p[i][0] = in.nextInt();
for (int i = 0; i < n; i++) {
p[i][1] = in.nextInt();
v[i] = p[i][1];
}
in.close();
Arrays.sort(v);
Arrays.sort(p, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
long[] xs = new long[n];
long[] cnt = new long[n];
long ans = 0;
for (int i = 0; i < n; i++) {
int pos = Arrays.binarySearch(v, p[i][1]);
ans += sum(cnt, pos) * p[i][0] - sum (xs, pos);
upd(cnt, pos, 1);
upd(xs, pos, p[i][0]);
}
System.out.println(ans);
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int mxn = 2e5 + 100;
pair<int, long long> a[mxn];
long long r[mxn], b1[mxn], b2[mxn], ans;
void add(long long *b, int idx, int val, int n) {
for (; idx <= n; idx += idx & -idx) b[idx] += val;
}
long long ask(long long *b, int idx) {
long long ret = 0;
for (; idx > 0; idx -= idx & -idx) ret += b[idx];
return ret;
}
int main() {
int n, m;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i].first);
for (int i = 1; i <= n; i++)
scanf("%lld", &a[i].second), r[i - 1] = a[i].second;
sort(r, r + n), m = unique(r, r + n) - r;
for (int i = 1; i <= n; i++)
a[i].second = lower_bound(r, r + m, a[i].second) - r + 1;
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; ++i) {
long long x = ask(b2, a[i].second), y = ask(b1, a[i].second);
ans += 1LL * y * a[i].first - x;
add(b2, a[i].second, a[i].first, n);
add(b1, a[i].second, 1, n);
}
printf("%lld\n", ans);
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long ans, n, a1[202020], a2[202020], od[202020];
pair<long long, long long> p[202020];
map<long long, long long> mp;
void gx1(long long x, long long v) {
for (long long i = x; i < 200200; i += i & -i) {
a1[i] += v;
}
}
void gx2(long long x, long long v) {
for (long long i = x; i < 200200; i += i & -i) {
a2[i] += v;
}
}
long long gt1(long long p) {
long long rt = 0;
for (long long i = p; i > 0; i -= i & -i) {
rt += a1[i];
}
return rt;
}
long long gt2(long long p) {
long long rt = 0;
for (long long i = p; i > 0; i -= i & -i) {
rt += a2[i];
}
return rt;
}
signed main() {
cin >> n;
for (long long i = 1; i <= n; i++) {
cin >> p[i].first;
}
for (long long i = 1; i <= n; i++) {
cin >> p[i].second;
od[i] = p[i].second;
}
sort(od + 1, od + n + 1);
sort(p + 1, p + n + 1);
long long pp = 1;
for (long long i = 1; i <= n; i++) {
if (!mp[od[i]]) {
mp[od[i]] = pp;
pp++;
}
}
for (long long i = 1; i <= n; i++) {
ans += p[i].first * gt1(mp[p[i].second]) - gt2(mp[p[i].second]);
gx1(mp[p[i].second], 1ll);
gx2(mp[p[i].second], p[i].first);
}
cout << ans << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
/*
Author: Anthony Ngene
Created: 30/09/2020 - 12:31
*/
import java.io.*;
import java.util.*;
public class F {
// checks: 1. edge cases 2. overflow 3. possible errors (e.g 1/0, arr[out]) 4. time/space complexity
void solver() throws IOException {
int n = in.intNext();
long[] dists = in.nextLongArray(n);
long mxDist = max(dists) + 1;
long[] speeds = in.nextLongArray(n);
Tuple[] items = new Tuple[n];
HashSet<Long> posSpeeds = new HashSet<>();
HashSet<Long> negSpeeds = new HashSet<>();
// List<Long> posSpeeds = new ArrayList<>();
// List<Long> negSpeeds = new ArrayList<>();
for (int i = 0; i < n; i++) {
items[i] = new Tuple(dists[i], speeds[i]);
long num = speeds[i];
posSpeeds.add(max(-1, num));
negSpeeds.add(max(-1, -num));
}
Arrays.sort(items);
// out.println(items);
// out.println(posSpeeds);
// out.println(negSpeeds);
List<Long> posList = new ArrayList<>(posSpeeds);
Collections.sort(posList);
HashMap<Long, Integer> posMap = new HashMap<>();
for (int i = 0; i < posList.size(); i++) posMap.put(posList.get(i), i + 1);
// out.println(posMap);
List<Long> negList = new ArrayList<>(negSpeeds);
Collections.sort(negList);
HashMap<Long, Integer> negMap = new HashMap<>();
for (int i = 0; i < negList.size(); i++) negMap.put(negList.get(i), i + 1);
// out.println(negMap);
BIT counts = new BIT(posList.size() + 2);
BIT distances = new BIT(posList.size() + 2);
long forward = 0;
for (int i = 0; i < n; i++) {
Tuple node = items[i];
long dist = node.a;
int speed = posMap.get(max(-1, node.b));
long prevCount = counts.getSum(speed);
long prevDist = distances.getSum(speed);
if (node.b >= 0)
forward += dist * prevCount - prevDist;
// out.pp(i, speed, prevCount, prevDist);
counts.update(speed, 1);
distances.update(speed, dist);
}
// out.println(forward);
int last = negList.size() + 1;
counts = new BIT(negList.size() + 2);
distances = new BIT(negList.size() + 2);
long backward = 0;
for (int i = n - 1; i >= 0; i--) {
Tuple node = items[i];
if (node.b >= 0) continue;
long dist = mxDist - node.a;
int speed = negMap.get(-node.b);
long prevCount = counts.getSum(speed);
long prevDist = distances.getSum(speed);
backward += dist * prevCount - prevDist;
counts.update(speed, 1);
distances.update(speed, dist);
}
// out.println(backward);
out.println(forward + backward);
}
static class BIT {
long[] tree;
int n;
public BIT(int n) {
tree = new long[n + 1];
this.n = n;
}
public BIT(long[] arr) {
this.n = arr.length;
tree = new long[n + 1];
for (int i = 1; i < n + 1; i++) {
tree[i] += arr[i-1];
int parent = i + (i & -i);
if (parent <= n) tree[parent] += tree[i];
}
}
public long getSum(int idx) {
// one indexed
long total = 0;
while (idx > 0) {
total += tree[idx];
idx = idx - (idx & -idx);
}
return total;
}
public long rangeSum(int a, int b) {
// a-b inclusive: b > a and one indexed.
return getSum(b) - getSum(a - 1);
}
public void update(int idx, long valueToAdd) {
// one indexed
while (idx <= n) {
tree[idx] += valueToAdd;
idx = idx + (idx & -idx);
}
}
}
// Generated Code Below:
private static final FastWriter out = new FastWriter();
private static FastScanner in;
static ArrayList<Integer>[] adj;
private static long e97 = (long)1e9 + 7;
public static void main(String[] args) throws IOException {
in = new FastScanner();
new F().solver();
out.close();
}
static class FastWriter {
private static final int IO_BUFFERS = 128 * 1024;
private final StringBuilder out;
public FastWriter() { out = new StringBuilder(IO_BUFFERS); }
public FastWriter p(Object object) { out.append(object); return this; }
public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }
public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }
public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(long[][] arr) { for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(int[][] arr) { for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(char[][] arr) { for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(double[][] arr) { for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public <T>void println(T[][] arr) { for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public FastWriter println(Object object) { out.append(object).append("\n"); return this; }
public void toFile(String fileName) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(out.toString());
writer.close();
}
public void close() throws IOException { System.out.print(out); }
}
static class FastScanner {
private InputStream sin = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
public FastScanner(){}
public FastScanner(String filename) throws FileNotFoundException {
File file = new File(filename);
sin = new FileInputStream(file);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = sin.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long longNext() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b) || b == ':'){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int intNext() {
long nl = longNext();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double doubleNext() { return Double.parseDouble(next());}
public long[] nextLongArray(final int n){
final long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = longNext();
return a;
}
public int[] nextIntArray(final int n){
final int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = intNext();
return a;
}
public double[] nextDoubleArray(final int n){
final double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = doubleNext();
return a;
}
public ArrayList<Integer>[] getAdj(int n) {
ArrayList<Integer>[] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
return adj;
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {
return adjacencyList(nodes, edges, false);
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {
adj = getAdj(nodes);
for (int i = 0; i < edges; i++) {
int a = intNext(), b = intNext();
adj[a].add(b);
if (!isDirected) adj[b].add(a);
}
return adj;
}
}
static class u {
public static int upperBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int upperBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }
static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }
static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }
private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }
private static void customSort(int[][] arr) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
return Integer.compare(a[0], b[0]);
}
});
}
public static int[] swap(int[] arr, int left, int right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static char[] swap(char[] arr, int left, int right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static int[] reverse(int[] arr, int left, int right) {
while (left < right) {
int temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return arr;
}
public static boolean findNextPermutation(int[] data) {
if (data.length <= 1) return false;
int last = data.length - 2;
while (last >= 0) {
if (data[last] < data[last + 1]) break;
last--;
}
if (last < 0) return false;
int nextGreater = data.length - 1;
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
data = swap(data, nextGreater, last);
data = reverse(data, last + 1, data.length - 1);
return true;
}
public static int biSearch(int[] dt, int target){
int left=0, right=dt.length-1;
int mid=-1;
while(left<=right){
mid = (right+left)/2;
if(dt[mid] == target) return mid;
if(dt[mid] < target) left=mid+1;
else right=mid-1;
}
return -1;
}
public static int biSearchMax(long[] dt, long target){
int left=-1, right=dt.length;
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt[mid] <= target) left=mid;
else right=mid;
}
return left;
}
public static int biSearchMaxAL(ArrayList<Integer> dt, long target){
int left=-1, right=dt.size();
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt.get(mid) <= target) left=mid;
else right=mid;
}
return left;
}
private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][] ob, int res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(long[][] ob, long res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(char[][] ob, char res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }
private static boolean same3(long a, long b, long c){
if(a!=b) return false;
if(b!=c) return false;
if(c!=a) return false;
return true;
}
private static boolean dif3(long a, long b, long c){
if(a==b) return false;
if(b==c) return false;
if(c==a) return false;
return true;
}
private static double hypotenuse(double a, double b){
return Math.sqrt(a*a+b*b);
}
private static long factorial(int n) {
long ans=1;
for(long i=n; i>0; i--){ ans*=i; }
return ans;
}
private static long facMod(int n, long mod) {
long ans=1;
for(long i=n; i>0; i--) ans = (ans * i) % mod;
return ans;
}
private static long lcm(long m, long n){
long ans = m/gcd(m,n);
ans *= n;
return ans;
}
private static long gcd(long m, long n) {
if(m < n) return gcd(n, m);
if(n == 0) return m;
return gcd(n, m % n);
}
private static boolean isPrime(long a){
if(a==1) return false;
for(int i=2; i<=Math.sqrt(a); i++){ if(a%i == 0) return false; }
return true;
}
static long modInverse(long a, long mod) {
/* Fermat's little theorem: a^(MOD-1) => 1
Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */
return binpowMod(a, mod - 2, mod);
}
static long binpowMod(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if (b % 2 == 1) res = (res * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return res;
}
private static int getDigit2(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf = 1<<d; }
return d;
}
private static int getDigit10(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf*=10; }
return d;
}
private static boolean isInArea(int y, int x, int h, int w){
if(y<0) return false;
if(x<0) return false;
if(y>=h) return false;
if(x>=w) return false;
return true;
}
private static ArrayList<Integer> generatePrimes(int n) {
int[] lp = new int[n + 1];
ArrayList<Integer> pr = new ArrayList<>();
for (int i = 2; i <= n; ++i) {
if (lp[i] == 0) {
lp[i] = i;
pr.add(i);
}
for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {
lp[i * pr.get(j)] = pr.get(j);
}
}
return pr;
}
static long nPrMod(int n, int r, long MOD) {
long res = 1;
for (int i = (n - r + 1); i <= n; i++) {
res = (res * i) % MOD;
}
return res;
}
static long nCr(int n, int r) {
if (r > (n - r))
r = n - r;
long ans = 1;
for (int i = 1; i <= r; i++) {
ans *= n;
ans /= i;
n--;
}
return ans;
}
static long nCrMod(int n, int r, long MOD) {
long rFactorial = nPrMod(r, r, MOD);
long first = nPrMod(n, r, MOD);
long second = binpowMod(rFactorial, MOD-2, MOD);
return (first * second) % MOD;
}
static void printBitRepr(int n) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < 32; i++) {
int mask = (1 << i);
res.append((mask & n) == 0 ? "0" : "1");
}
out.println(res);
}
static String bitString(int n) {return Integer.toBinaryString(n);}
static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed
static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }
static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }
static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }
static HashMap<Character, Integer> counts(String word) {
HashMap<Character, Integer> counts = new HashMap<>();
for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);
return counts;
}
static HashMap<Integer, Integer> counts(int[] arr) {
HashMap<Integer, Integer> counts = new HashMap<>();
for (int value : arr) counts.merge(value, 1, Integer::sum);
return counts;
}
static HashMap<Long, Integer> counts(long[] arr) {
HashMap<Long, Integer> counts = new HashMap<>();
for (long l : arr) counts.merge(l, 1, Integer::sum);
return counts;
}
static HashMap<Character, Integer> counts(char[] arr) {
HashMap<Character, Integer> counts = new HashMap<>();
for (char c : arr) counts.merge(c, 1, Integer::sum);
return counts;
}
static long hash(int x, int y) {
return x* 1_000_000_000L +y;
}
static final Random random = new Random();
static void sort(int[] a) {
int n = a.length;// shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void sort(long[] arr) {
shuffleArray(arr);
Arrays.sort(arr);
}
static void shuffleArray(long[] arr) {
int n = arr.length;
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + random.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
}
static class Tuple implements Comparable<Tuple> {
long a;
long b;
long c;
public Tuple(long a, long b) {
this.a = a;
this.b = b;
this.c = 0;
}
public Tuple(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
public long getA() { return a; }
public long getB() { return b; }
public long getC() { return c; }
public int compareTo(Tuple other) {
if (this.a == other.a) {
if (this.b == other.b) return Long.compare(this.c, other.c);
return Long.compare(this.b, other.b);
}
return Long.compare(this.a, other.a);
}
@Override
public int hashCode() { return Arrays.deepHashCode(new Long[]{a, b, c}); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Tuple)) return false;
Tuple pairo = (Tuple) o;
return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);
}
@Override
public String toString() { return String.format("(%d %d %d) ", this.a, this.b, this.c); }
}
private static int abs(int a){ return (a>=0) ? a: -a; }
private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }
private static long abs(long a){ return (a>=0) ? a: -a; }
private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }
private static double abs(double a){ return (a>=0) ? a: -a; }
private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
import sys
input = sys.stdin.readline
from heapq import heappush, heappop, heapify
def query(f, i):
ret = [0, 0]
while i:
ret[0] += f[i][0]
ret[1] += f[i][1]
i -= (i & -i)
return ret
def update(f, i, d):
n = len(f)
while i < n:
f[i][0] += d[0]
f[i][1] += d[1]
i += (i & -i)
n = int(input())
x = list(map(int, input().split()))
v = list(map(int, input().split()))
a = [()] * (n+1)
for i in range(1, n+1):
a[i] = (x[i-1], v[i-1])
a.sort()
f = [[0, 0] for i in range(n+1)]
for i in range(1, n+1):
update(f, i, [a[i][0], 1])
b = []
for i in range(1, n+1):
b.append((-a[i][1], -i))
heapify(b)
ans = 0
while b:
v, i = heappop(b)
v, i = -v, -i
x = a[i][0]
if i > 1:
sum, cnt = query(f, i-1)
ans += x * cnt - sum
update(f, i, [-x, -1])
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
int dddx[] = {1, -1, 0, 0, 1, 1, -1, -1};
int dddy[] = {0, 0, 1, -1, 1, -1, 1, -1};
vector<pair<long long int, long long int> > vec;
int n;
long long int tree[(int)(2 * 1e5 + 1)], tree2[(int)(2 * 1e5 + 1)];
void atualiza(int x, int v) {
for (; x < n; x = x | (x + 1)) tree[x] += v;
}
void atualiza2(int x, int v) {
for (; x < n; x = x | (x + 1)) tree2[x] += v;
}
long long int sum(long long int x) {
long long int s = 0;
for (; x >= 0; x = (x & (x + 1)) - 1) s += tree[x];
return s;
}
long long int sum2(int x) {
long long int s = 0;
for (; x >= 0; x = (x & (x + 1)) - 1) s += tree2[x];
return s;
}
void compress() {
vector<int> aux2;
for (int i = 0; i < n; i++) aux2.push_back(vec[i].second);
sort(aux2.begin(), aux2.end());
for (int j = 0; j < n; j++) {
auto i = vec[j];
vec[j].second =
lower_bound(aux2.begin(), aux2.end(), i.second) - aux2.begin();
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
vector<int> aux;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
vec.push_back({a, 1});
}
for (int i = 0; i < n; i++) {
int a;
cin >> a;
vec[i].second = a;
}
sort(vec.begin(), vec.end());
compress();
for (int i = 0; i < n; i++) aux.push_back(vec[i].second);
sort(aux.begin(), aux.end());
long long int ans = 0;
for (int i = 0; i < n; i++) {
int pos = lower_bound(aux.begin(), aux.end(), vec[i].second) - aux.begin();
ans += (sum2(pos) * vec[i].first - sum(pos));
atualiza(pos, vec[i].first);
atualiza2(pos, 1);
}
cout << ans << "\n";
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
PrintWriter out;
InputReader in;
long[][] segtree;
final Comparator<Tuple> com = new Comparator<Tuple>() {
public int compare(Tuple t1, Tuple t2) {
if (t1.x != t2.x)
return Integer.compare(t1.x, t2.x);
else
return Integer.compare(t1.y, t2.y);
}
};
long merge(long x, long y) {
return x + y;
}
void segtree_update(int ind, long val, int n) {
ind += n;
for (segtree[0][ind] += val, segtree[1][ind]++; ind > 1; ind >>= 1) {
segtree[0][ind >> 1] = merge(segtree[0][ind], segtree[0][ind ^ 1]);
segtree[1][ind >> 1] = merge(segtree[1][ind], segtree[1][ind ^ 1]);
}
}
long[] segtree_query(int l, int r, int n) {
long res = 0;
long cnt = 0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) {
res = merge(res, segtree[0][l]);
cnt = merge(cnt, segtree[1][l]);
l++;
}
if ((r & 1) == 1) {
--r;
res = merge(res, segtree[0][r]);
cnt = merge(cnt, segtree[1][r]);
}
}
return new long[]{res, cnt};
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.out = out;
this.in = in;
int n = ni();
Tuple[] arr = new Tuple[n];
int i = 0;
segtree = new long[2][2 * n];
HashMap<Integer, Integer> hmap = new HashMap<>();
for (i = 0; i < n; i++)
arr[i] = new Tuple(ni(), -1);
TreeSet<Integer> tset = new TreeSet<>();
for (i = 0; i < n; i++) {
arr[i] = new Tuple(arr[i].x, ni());
tset.add(arr[i].y);
}
Arrays.sort(arr, com);
int c = 0;
for (int x : tset)
hmap.put(x, c++);
long ans = 0;
for (i = n - 1; i >= 0; i--) {
long[] curr_query = segtree_query(hmap.get(arr[i].y), c, c);
ans += curr_query[0] - arr[i].x * curr_query[1];
segtree_update(hmap.get(arr[i].y), arr[i].x, c);
}
pn(ans);
}
int ni() {
return in.nextInt();
}
void pn(long zx) {
out.println(zx);
}
class Tuple {
int x;
int y;
Tuple(int a, int b) {
x = a;
y = b;
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class CF1311F extends PrintWriter {
CF1311F() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1311F o = new CF1311F(); o.main(); o.flush();
}
int[] ll, rr, zz, key, val, cnt; long[] sum; int l_, r_, __ = 1;
Random rand = new Random();
void init(int n) {
ll = new int[1 + n]; rr = new int[1 + n]; zz = new int[1 + n];
key = new int[1 + n]; val = new int[1 + n];
cnt = new int[1 + n]; sum = new long[1 + n];
}
int node(int v, int x) {
zz[__] = rand.nextInt();
key[__] = v; val[__] = x; cnt[__] = 1; sum[__] = x;
return __++;
}
void pul(int u) {
int l = ll[u], r = rr[u];
cnt[u] = cnt[l] + 1 + cnt[r];
sum[u] = sum[l] + val[u] + sum[r];
}
void split(int u, int k) {
if (u == 0) {
l_ = r_ = 0;
return;
}
if (key[u] <= k) {
split(rr[u], k);
rr[u] = l_; l_ = u;
} else {
split(ll[u], k);
ll[u] = r_; r_ = u;
}
pul(u);
}
int merge(int u, int v) {
if (u == 0)
return v;
if (v == 0)
return u;
if (zz[u] < zz[v]) {
rr[u] = merge(rr[u], v);
pul(u);
return u;
} else {
ll[v] = merge(u, ll[v]);
pul(v);
return v;
}
}
static class P {
int x, v;
}
void main() {
int n = sc.nextInt();
P[] pp = new P[n];
for (int i = 0; i < n; i++)
pp[i] = new P();
for (int i = 0; i < n; i++)
pp[i].x = sc.nextInt();
for (int i = 0; i < n; i++)
pp[i].v = sc.nextInt();
Arrays.sort(pp, (p, q) -> p.x - q.x);
init(n);
long ans = 0;
int u_ = 0;
for (int i = 0; i < n; i++) {
int x = pp[i].x, v = pp[i].v;
split(u_, v);
ans += (long) cnt[l_] * x - sum[l_];
u_ = merge(l_, merge(node(v, x), r_));
}
println(ans);
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class C {
static int a, b, c;
static int solve(int[] ans, int min, int i, int d) {
int curr = Math.abs(i - b);
curr += Math.abs(d - a);
int r = c % i;
if (c < i)
curr += i - c;
else
curr += Math.min(r, i - r);
if (curr < min) {
ans[0] = d;
ans[1] = i;
if (c < i)
ans[2] = i;
else
ans[2] = r < i - r ? c - r : c - r + i;
}
return curr;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[][] a = new int[n][2];
TreeMap<Integer, Integer> map = new TreeMap();
for (int i = 0; i < n; i++) {
a[i][0] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
a[i][1] = sc.nextInt();
map.put(a[i][1], 1);
}
int id = 1;
for (int x : map.keySet())
map.put(x, id++);
FenwickTree ft = new FenwickTree(map.size());
Arrays.sort(a, (x, y) -> x[0] - y[0]);
long ans = 0;
for (int[] pair : a) {
int x = pair[0], v = pair[1];
long[] less = ft.query(map.get(v));
long cnt = less[0];
ans += x * cnt - less[1];
ft.udpate(map.get(v), new int[] { 1, x });
}
out.println(ans);
out.close();
}
static class FenwickTree {
long[][] bit;
FenwickTree(int n) {
bit = new long[n + 1][2];
}
void udpate(int idx, int[] a) {
while (idx < bit.length) {
for (int j = 0; j < 2; j++)
bit[idx][j] += a[j];
idx += idx & -idx;
}
}
long[] query(int idx) {
long[] ans = new long[2];
while (idx > 0) {
for (int j = 0; j < 2; j++)
ans[j] += bit[idx][j];
idx -= idx & -idx;
}
return ans;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct hash_pair {
template <class T1, class T2>
size_t operator()(const pair<T1, T2>& p) const {
auto hash1 = hash<T1>{}(p.first);
auto hash2 = hash<T2>{}(p.second);
return hash1 ^ hash2;
}
};
bool prime[10000001];
long long P = 1000000007 - 2;
long long factorial[10000001] = {0};
long long powerFunction(long long x, long long y) {
long long res = 1;
long long p = 1000000007;
x = x % p;
while (y > 0) {
if (y & 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
void sieveFunction(long long maxLimit) {
memset(prime, true, sizeof(prime));
prime[0] = prime[1] = false;
for (long long i = 2; maxLimit >= i; i++) {
if (prime[i]) {
for (long long j = 2 * i; maxLimit >= j; j += i) prime[j] = false;
}
}
}
void factorialFunction(long long maxLimit) {
factorial[0] = 1;
for (long long i = 1; i <= maxLimit; i++)
factorial[i] = (factorial[i - 1] * i) % 1000000007;
return;
}
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
vector<pair<long long, long long>> tree[800001];
vector<long long> treesum[800001];
vector<pair<long long, long long>> v;
void build(long long node, long long start, long long end) {
if (start == end) {
vector<pair<long long, long long>> temp;
temp.push_back({v[start].second, v[start].first});
tree[node] = temp;
vector<long long> sum;
long long s = 0;
for (long long i = 0; tree[node].size() > i; i++) {
s += tree[node][i].second;
treesum[node].push_back(s);
}
return;
}
long long mid = (start + end) / 2;
build(2 * node, start, mid);
build(2 * node + 1, mid + 1, end);
long long i = 0, j = 0;
while (i < tree[2 * node].size() && j < tree[2 * node + 1].size()) {
if (tree[2 * node][i] <= tree[2 * node + 1][j]) {
tree[node].push_back(tree[2 * node][i]);
i++;
} else {
tree[node].push_back(tree[2 * node + 1][j]);
j++;
}
}
for (long long k = i; k < tree[2 * node].size(); k++)
tree[node].push_back(tree[2 * node][k]);
for (long long k = j; k < tree[2 * node + 1].size(); k++)
tree[node].push_back(tree[2 * node + 1][k]);
long long s = 0;
for (long long k = 0; tree[node].size() > k; k++) {
s += tree[node][k].second;
treesum[node].push_back(s);
}
}
long long n;
long long SEC;
long long query(long long node, long long start, long long end, long long x) {
if (start > x && end <= n) {
pair<long long, long long> tem = {v[x].second, INT64_MIN};
long long id = lower_bound(tree[node].begin(), tree[node].end(), tem) -
tree[node].begin();
if (id) {
SEC += (long long)tree[node].size() - id;
return treesum[node].back() - treesum[node][id - 1];
}
SEC += tree[node].size();
return treesum[node].back();
}
if (end <= x || start > n) {
return 0;
}
long long mid = (start + end) / 2;
return query(2 * node, start, mid, x) + query(2 * node + 1, mid + 1, end, x);
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
cin >> n;
long long x[n + 1], s[n + 1];
for (long long i = 1; n >= i; i++) {
cin >> x[i];
}
for (long long i = 1; n >= i; i++) {
cin >> s[i];
}
v.push_back({INT64_MIN, INT64_MIN});
for (long long i = 1; n >= i; i++) {
v.push_back({x[i], s[i]});
}
sort(v.begin(), v.end());
build(1, 1, n);
long long ans = 0;
for (long long i = 1; n >= i; i++) {
SEC = 0;
long long xx = v[i].first;
long long temp = query(1, 1, n, i);
temp -= xx * SEC;
ans += temp;
}
cout << ans << "\n";
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
import bisect
import sys
class ft:
def __init__(self,n):
self.a = [0]*(200000)
self.n = n
def qry(self,r):
ret = 0
while r>=0:
ret+=self.a[r]
r=(r&(r+1))-1
return ret
def upd(self,i,v):
while i<self.n:
self.a[i]+=v
i=(i|(i+1))
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
n = int(input())
x = list(map(int,input().split()))
v = list(map(int,input().split()))
f0 = ft(n)
f1 = ft(n)
a1 = [[] for _ in range(n)]
for i in range(n):
a1[i].append(x[i])
a1[i].append(v[i])
a1.sort()
v.sort()
ans = 0
for i in range(n):
p = bisect.bisect_left(v,a1[i][1])
ans+=(f0.qry(p)*a1[i][0])-(f1.qry(p));
f0.upd(p,1)
f1.upd(p,a1[i][0])
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1311F
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int[] pos = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
pos[i] = Integer.parseInt(st.nextToken());
int[] vel = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
vel[i] = Integer.parseInt(st.nextToken());
//int maxVel = compress(vel);
//sort by position
//count how many velocities are greater
Point[] arr = new Point[N];
for(int i=0; i < N; i++)
arr[i] = new Point(pos[i], vel[i]);
Arrays.sort(arr);
sort(pos);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
long res = 0L;
for(int k=0; k < N; k++)
{
map.put(pos[k],k);
res += (long)pos[k]*(long)(-1*N+1+2*k);
}
for(int k=0; k < N; k++)
{
if(k < map.get(arr[k].pos))
res -= (long)arr[k].pos*(long)(map.get(arr[k].pos)-k);
else if(k > map.get(arr[k].pos))
res += (long)arr[k].pos*(long)(k-map.get(arr[k].pos));
}
System.out.println(res);
}
public static int compress(int[] vel)
{
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: vel)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1;
for(int x: ls)
if(!map.containsKey(x))
map.put(x, boof++);
for(int i=0; i < vel.length; i++)
vel[i] = map.get(vel[i]);
return boof-1;
}
public static void sort(int[] arr)
{
//stable heap sort
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int a: arr)
pq.add(a);
for(int i=0; i < arr.length; i++)
arr[i] = pq.poll();
}
}
class Point implements Comparable<Point>
{
public int pos;
public int vel;
public Point(int a, int b)
{
pos = a;
vel = b;
}
public int compareTo(Point oth)
{
if(vel != oth.vel)
return vel-oth.vel;
return pos-oth.pos;
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
long long int savev[maxn];
struct node {
long long int x, v;
node(){};
node(long long int x, long long int v) : x(x), v(v){};
bool operator<(const node& n) const { return x < n.x; }
} save[maxn];
map<long long int, long long int> getv;
long long int stree[maxn];
long long int vtree[maxn];
long long int n;
void add(long long int x, long long int d, long long int* tree) {
while (x <= n) {
tree[x] += d;
x += (x & (-x));
}
}
long long int sum(long long int x, long long int* tree) {
long long int sum = 0;
while (x > 0) {
sum += tree[x];
x -= (x & (-x));
}
return sum;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
scanf("%lld", &save[i].x);
}
for (int i = 1; i <= n; i++) {
scanf("%lld", &save[i].v);
savev[i] = save[i].v;
}
sort(savev + 1, savev + 1 + n);
sort(save + 1, save + 1 + n);
int vcnt = 0;
for (int i = 1; i <= n; i++) {
if (!getv[savev[i]]) {
getv[savev[i]] = ++vcnt;
}
}
long long int ans = 0;
for (int i = 1; i <= n; i++) {
node& nownode = save[i];
long long int nowv = getv[nownode.v];
long long int sumdis = sum(nowv, vtree);
long long int sumsmall = sum(nowv, stree);
ans += nownode.x * sumsmall - sumdis;
add(nowv, nownode.x, vtree);
add(nowv, 1, stree);
}
printf("%lld", ans);
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long max(long long a, long long b) { return a > b ? a : b; }
void swap(long long& a, long long& b) {
long long tmp = a;
a = b;
b = tmp;
}
long long t, n;
long long x[200006], v[200006];
pair<long long, long long> xv[200006];
long long prfxSum[200006];
pair<long long, long long> sgmTree[4 * 200006];
pair<long long, long long> get(long long node, long long st, long long en,
long long pos) {
if (st > en) {
return make_pair(0, 0);
}
if (en == pos) {
return sgmTree[node];
}
if ((st + en) / 2 >= pos) {
return get(2 * node, st, (st + en) / 2, pos);
} else {
pair<long long, long long> to_ret =
get(2 * node + 1, (st + en) / 2 + 1, en, pos);
return make_pair(sgmTree[2 * node].first + to_ret.first,
sgmTree[2 * node].second + to_ret.second);
}
}
void remove(long long node, long long st, long long en, long long pos) {
if (st > en) {
return;
}
if (st == en) {
sgmTree[node] = make_pair(0, 0);
return;
}
if ((st + en) / 2 >= pos) {
remove(2 * node, st, (st + en) / 2, pos);
} else {
remove(2 * node + 1, (st + en) / 2 + 1, en, pos);
}
sgmTree[node].first = sgmTree[2 * node].first + sgmTree[2 * node + 1].first;
sgmTree[node].second =
sgmTree[2 * node].second + sgmTree[2 * node + 1].second;
}
void buildtree(long long node, long long st, long long en) {
if (st > en) {
return;
}
if (st == en) {
sgmTree[node] = make_pair(x[st], 1);
return;
}
buildtree(2 * node, st, (st + en) / 2);
buildtree(2 * node + 1, (st + en) / 2 + 1, en);
sgmTree[node].first = sgmTree[2 * node].first + sgmTree[2 * node + 1].first;
sgmTree[node].second =
sgmTree[2 * node].second + sgmTree[2 * node + 1].second;
}
void solve() {
cin >> n;
for (int i = 1; i <= 4 * n; ++i) {
sgmTree[i] = make_pair(0, 0);
}
for (int i = 1; i <= n; ++i) {
cin >> x[i];
}
for (int i = 1; i <= n; ++i) {
cin >> v[i];
}
for (int i = 1; i <= n; ++i) {
xv[i] = make_pair(x[i], v[i]);
}
sort(xv + 1, xv + 1 + n);
for (int i = 1; i <= n; ++i) {
x[i] = xv[i].first;
}
for (int i = 1; i <= n; ++i) {
v[i] = xv[i].second;
}
priority_queue<pair<long long, long long> > pq;
for (int i = 1; i <= n; ++i) {
pq.push(make_pair(v[i], i));
}
prfxSum[1] = x[1];
for (int i = 2; i <= n; ++i) {
prfxSum[i] = prfxSum[i - 1] + x[i];
}
buildtree(1, 1, n);
long long ans = 0;
while (!pq.empty()) {
pair<long long, long long> pair = pq.top();
long long mxv = pair.first;
long long pos = pair.second;
pq.pop();
long long val = 0;
val += get(1, 1, n, pos).first;
val -= get(1, 1, n, pos).second * x[pos];
remove(1, 1, n, pos);
if (val < 0) {
val *= -1;
}
ans += val;
}
cout << ans << endl;
return;
}
int main(int argc, char const* argv[]) {
t = 1;
while (t--) {
solve();
}
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.awt.*;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.text.DecimalFormat;
public class Exam {
public static long mod = (long)Math.pow(10, 9)+7 ;
public static double epsilon=0.00000000008854;//value of epsilon
public static InputReader sc = new InputReader(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static long gcd(long a,long b){
while(b>0){
long t=b;
b=a%b;
a=t;
}
return a;
}
static void dfs(Point p[],int v,boolean vis[]){
if (vis[v])return;
vis[v]=true;
for (int i=0;i<p.length;i++){
if (p[i].x==p[v].x || p[i].y==p[v].y){
dfs(p,i,vis);
}
}
}
public static long bSearch(Pair[]d, int l, int r, int a) {
if(d[l].d > a)
return 0;
if(l == r)
return d[l].g;
int m = (l + r + 1) / 2;
if(d[m].d > a)
return bSearch(d, l, m - 1, a);
return bSearch(d, m, r, a);
}
static class Pair implements Comparable<Pair> {
int d, i;
long g;
public Pair(int D, long G, int I) {
d = D;
g = G;
i = I;
}
public int compareTo(Pair p) {
if(d == p.d)
return i - p.i;
return d - p.d;
}
}
public static long pow(long x,long y,long mod){
long ans=1;
while(y>0){
if((y&1)==1){
ans=(ans*x)%mod;
}
y=y>>1;
x=(x*x)%mod;
}
return ans;
}
public static boolean isPalindrome(String s1,String s2){
s2=reverseString(s2);
if(s1.equals(s2)){
return true;
}
else
return false;
/*
boolean f=true;
for(int i=0;i<s.length();i++){
if(i>s.length()-i-1)
break;
if(s.charAt(i)!=s.charAt(s.length()-i-1)){
f=false;
break;
}
}
return f;*/
}
public static HashSet<Long> query(int root,int l,int r,int st,int en,ArrayList<HashSet<Long>>s){
if(l>=st&&r<=en){
return s.get(root);
}
else if(r<st||l>en)
return new HashSet<Long>();
else{
HashSet<Long> h1=query(2*root+1, l, (l+r)/2, st, en, s);
HashSet<Long> h2=query(2*root+2, (l+r)/2+1, r, st, en, s);
HashSet<Long> h=new HashSet<>();
h.addAll(h1);h.addAll(h2);
return h;
}
}
public static void main(String[] args) {
// code starts..
//int q=sc.nextInt();
//while(q-->0){
int n=sc.nextInt();
//int m=sc.nextInt();
Long a[][]=new Long[n][3];
for(int i=0;i<n;i++){
a[i][0]=sc.nextLong();
}
for(int i=0;i<n;i++){
a[i][1]=sc.nextLong();
}
Arrays.sort(a,column(0));
for(int i=0;i<n;i++){
a[i][2]=(long)i+1;
}
Arrays.sort(a,column());
Bit co=new Bit(1000000);
Bit sum=new Bit(1000000);
long tot=0;
for(int i=0;i<n;i++){
//if(i>0&&a[i][1]==a[i-1][1]){
// if(a[i][0]>a[i-1][0])
// tot-=a[i][0]-a[i-1][0];
//}
long count=co.query(a[i][2]);
long s=sum.query(a[i][2]);
tot+=(long)count*a[i][0]-s;
co.update(a[i][2], 1);
sum.update(a[i][2], a[i][0]);
}
pw.println(tot);
//}
// Code ends...
pw.flush();
pw.close();
}
static class tripletL implements Comparable<tripletL> {
Long x, y, z;
tripletL(long x, long y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(tripletL o) {
int result = x.compareTo(o.x);
if (result == 0)
result = y.compareTo(o.y);
if (result == 0)
result = z.compareTo(o.z);
return result;
}
public boolean equlas(Object o) {
if (o instanceof tripletL) {
tripletL p = (tripletL) o;
return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0);
}
return false;
}
public String toString() {
return x + " " + y + " " + z;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode();
}
}
public static String Doubleformate(double a,int n){
String s="";
while(n-->0){
s+='0';
}
DecimalFormat f =new DecimalFormat("#0."+s);
return f.format(a);
}
public static Comparator<Long[]> column(int i){
return
new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
return o1[i].compareTo(o2[i]);//for ascending
//return o2[i].compareTo(o1[i]);//for descending
}
};
}
public static Comparator<Long[]> column(){
return
new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
if(o1[1]!=o2[1])
return o1[1].compareTo(o2[1]);//for ascending
//return o2[i].compareTo(o1[i]);//for descending
else return o1[0].compareTo(o2[0]);
}
};
}
public static Comparator<Long[]> pair(){
return
new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
int result=o1[0].compareTo(o2[0]);
if(result==0)
result=o1[1].compareTo(o2[1]);
return result;
}
};
}
public static Comparator<Long[]> Triplet(){
return
new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
for(int i=0;i<3;i++){
for(int j=i+1;j<3;j++){
for(int k=0;k<3;k++){
for(int p=k+1;p<3;p++){
if((o1[i]==o2[k]&&o1[j]==o2[p])||(o1[j]==o2[k]&&o1[i]==o2[p])){
}
}
}
}
}
int result=o1[0].compareTo(o2[0]);
if(result==0)
result=o1[1].compareTo(o2[1]);
if(result==0)
result=o1[2].compareTo(o2[2]);
return result;
}
};
}
public static String reverseString(String s){
StringBuilder input1 = new StringBuilder();
input1.append(s);
input1 = input1.reverse();
return input1.toString();
}
public static int[] scanArray(int n){
int a[]=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
return a;
}
public static long[] scanLongArray(int n){
long a[]=new long [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
return a;
}
public static String [] scanStrings(int n){
String a[]=new String [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLine();
return a;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
class Bit{//1...n
long a[];
Bit(int n){
a=new long[n+1];
}
void update(long f,long delta){
int i=(int)f;
while(i<a.length){
a[i]+=delta;
i+=i&(-i);
}
}
long query(long f){
int i=(int)f;
long sum=0;
while(i>0){
sum+=a[i];
i-=i&(-i);
}
return sum;
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
struct Node {
int x, v;
bool operator<(const Node &rhs) const { return x < rhs.x; }
} p[maxn];
int b[maxn], n, to;
long long t[maxn], tt[maxn];
inline int lowbit(int x) { return x & -x; }
void update(long long *t, int x, int v) {
for (; x <= n; x += lowbit(x)) {
t[x] += v;
}
}
long long query(long long *t, int x) {
long long sum = 0;
for (; x; x -= lowbit(x)) {
sum += t[x];
}
return sum;
}
int find(int x) { return lower_bound(b + 1, b + to + 1, x) - b; }
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%d", &p[i].x);
for (int i = 1; i <= n; ++i) {
scanf("%d", &p[i].v);
b[i] = p[i].v;
}
sort(p + 1, p + n + 1);
sort(b + 1, b + n + 1);
to = unique(b + 1, b + n + 1) - b - 1;
long long ans = 0;
for (int i = 1; i <= n; ++i) {
int v = find(p[i].v);
ans += 1LL * query(tt, v) * p[i].x - query(t, v);
update(t, v, p[i].x);
update(tt, v, 1);
}
printf("%lld\n", ans);
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
void dout() { cerr << '\n'; }
template <typename Head, typename... Tail>
void dout(Head H, Tail... T) {
cerr << " " << H;
dout(T...);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 2e5 + 7;
int n, m, cnt[N];
long long sum[N];
pair<int, int> p[N];
void upd(int x, int y) {
for (; x <= m; x |= (x + 1)) {
cnt[x]++;
sum[x] += y;
}
}
int getnum(int x) {
int res = 0;
for (; x >= 0; x = (x & (x + 1)) - 1) {
res += cnt[x];
}
return res;
}
long long getsum(int x) {
long long res = 0;
for (; x >= 0; x = (x & (x + 1)) - 1) {
res += sum[x];
}
return res;
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
cin >> n;
vector<int> vec, v;
for (int i = 1; i <= n; i++) {
cin >> p[i].first;
}
for (int i = 1; i <= n; i++) {
cin >> p[i].second;
vec.push_back(p[i].second);
}
sort((vec).begin(), (vec).end());
map<int, int> ind;
for (int i = 1; i <= n; i++) {
if (!ind.count(vec[i - 1])) {
ind[vec[i - 1]] = ++m;
}
}
for (int i = 1; i <= n; i++) {
p[i].second = ind[p[i].second];
}
sort(p + 1, p + n + 1);
long long ans = 0;
for (int i = 1; i <= n; i++) {
ans += (long long)getnum(p[i].second) * p[i].first - getsum(p[i].second);
upd(p[i].second, p[i].first);
}
cout << ans;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n=int(input())
l=list(map(int,input().split()))
s=list(map(int,input().split()))
d1=defaultdict(list)
for i in range(n):
d1[l[i]].append(s[i])
s.sort()
d=defaultdict(list)
for i in range(n):
d[s[i]].append(i)
for i in d:
d[i].sort()
d[i]=deque(d[i])
l.sort()
u=[0]*n
u1=[0]*n
s=SegmentTree(u)
s1=SegmentTree(u1)
ans=0
for i in range(n):
sp=d1[l[i]][-1]
d1[l[i]].pop()
pos=d[sp][0]
#print(pos,sp)
d[sp].popleft()
ans+=s.query(0,pos-1)*l[i]-s1.query(0,pos-1)
s.__setitem__(pos,1)
s1.__setitem__(pos,l[i])
#print(ans)
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int n;
pair<int, int> a[maxn];
int m;
vector<int> v;
struct fenwick {
long long val[maxn];
void init() { fill(begin(val), end(val), 0); }
void upd(int x, int k) {
for (; x < maxn; x += x & -x) val[x] += k;
}
long long get(int x) {
long long res = 0;
for (; x > 0; x -= x & -x) res += val[x];
return res;
}
long long get(int l, int r) {
if (l > r) return 0;
return get(r) - get(l - 1);
}
} tree_tot, tree_cnt;
void read_input() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i].first;
for (int i = 1; i <= n; ++i) cin >> a[i].second;
}
void init() {
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; ++i) v.push_back(a[i].second);
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
m = v.size();
for (int i = 1; i <= n; ++i)
a[i].second = lower_bound(v.begin(), v.end(), a[i].second) - v.begin() + 1;
tree_tot.init();
tree_cnt.init();
for (int i = 1; i <= n; ++i) {
tree_tot.upd(a[i].second, a[i].first);
tree_cnt.upd(a[i].second, 1);
}
}
void solve() {
long long ans = 0;
for (int i = 1; i <= n; ++i) {
tree_tot.upd(a[i].second, -a[i].first);
tree_cnt.upd(a[i].second, -1);
ans += tree_tot.get(a[i].second, m) -
a[i].first * 1LL * tree_cnt.get(a[i].second, m);
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
read_input();
init();
solve();
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int N;
pair<signed long long, signed long long> P[202020];
pair<signed long long, signed long long> Q[202020];
template <class V, int ME>
class BIT {
public:
V bit[1 << ME];
V operator()(int e) {
if (e < 0) return 0;
V s = 0;
e++;
while (e) s += bit[e - 1], e -= e & -e;
return s;
}
void add(int e, V v) {
e++;
while (e <= 1 << ME) bit[e - 1] += v, e += e & -e;
}
};
BIT<signed long long, 20> bt, bt2;
void solve() {
int i, j, k, l, r, x, y;
string s;
cin >> N;
for (i = 0; i < (N); i++) cin >> P[i].first;
for (i = 0; i < (N); i++) cin >> P[i].second;
sort(P, P + N);
signed long long ret = 0;
for (i = 0; i < (N); i++) Q[i] = {P[i].second, i};
sort(Q, Q + N);
for (i = 0; i < (N); i++) {
ret += bt(Q[i].second) * P[Q[i].second].first;
bt.add(Q[i].second, 1);
}
reverse(Q, Q + N);
for (i = 0; i < (N); i++) {
ret -= (bt2(N) - bt2(Q[i].second)) * P[Q[i].second].first;
bt2.add(Q[i].second, 1);
}
cout << ret << endl;
}
int main(int argc, char** argv) {
string s;
int i;
if (argc == 1) ios::sync_with_stdio(false), cin.tie(0);
for (i = 0; i < (argc - 1); i++) s += argv[i + 1], s += '\n';
for (i = 0; i < (s.size()); i++) ungetc(s[s.size() - 1 - i], stdin);
cout.tie(0);
solve();
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
bool comp(pair<long long, long long> p1, pair<long long, long long> p2) {
if (p1.second == p2.second) return p1.first < p2.first;
return p1.second < p2.second;
}
signed main() {
long long n;
cin >> n;
vector<pair<long long, long long> > v(n);
for (long long i = 0; i < n; i++) {
cin >> v[i].first;
}
for (long long i = 0; i < n; i++) {
cin >> v[i].second;
}
sort(v.begin(), v.end());
map<long long, long long> mp;
long long ans = 0;
for (long long i = 0; i < n; i++) {
ans += (2 * i - n + 1) * v[i].first;
mp[v[i].first] = i;
}
sort(v.begin(), v.end(), comp);
for (long long i = 0; i < n; i++) {
ans += (i - mp[v[i].first]) * v[i].first;
}
cout << ans << endl;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long get(vector<long long> &f, int pos) {
long long res = 0;
for (; pos >= 0; pos = (pos & (pos + 1)) - 1) res += f[pos];
return res;
}
void upd(vector<long long> &f, int pos, int val) {
for (; pos < int(f.size()); pos |= pos + 1) {
f[pos] += val;
}
}
int main() {
int n;
cin >> n;
vector<pair<int, int>> p(n);
for (auto &pnt : p) cin >> pnt.first;
for (auto &pnt : p) cin >> pnt.second;
sort(p.begin(), p.end());
vector<int> vs;
for (auto &pnt : p) vs.push_back(pnt.second);
sort(vs.begin(), vs.end());
vs.resize(unique(vs.begin(), vs.end()) - vs.begin());
long long ans = 0;
vector<long long> cnt(vs.size()), xs(vs.size());
for (auto &pnt : p) {
int pos = lower_bound(vs.begin(), vs.end(), pnt.second) - vs.begin();
ans += get(cnt, pos) * 1ll * pnt.first - get(xs, pos);
upd(cnt, pos, 1);
upd(xs, pos, pnt.first);
}
cout << ans << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
pair<long long, long long> o[(int)2e5 + 10];
long long n, ts[(int)2e5 + 10], tc[(int)2e5 + 10];
int main(void) {
scanf("%lld", &n);
for (long long i = 0; i < n; i++) {
scanf("%lld", &o[i].second);
}
for (long long i = 0; i < n; i++) {
scanf("%lld", &o[i].first);
}
sort(o, o + n);
for (long long i = 0; i < n; i++) {
o[i] = {o[i].second, i + 1};
}
sort(o, o + n);
long long ans = 0;
for (long long i = 0; i < n; i++) {
long long r = o[i].second, idx = o[i].first;
long long s = 0, c = 0;
while (0 < r) {
s += ts[r];
c += tc[r];
r -= (r & -r);
}
ans += idx * c - s;
long long v = o[i].second;
while (v <= n) {
ts[v] += idx;
tc[v]++;
v += (v & -v);
}
}
printf("%lld\n", ans);
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 200000 + 50;
const long long LIM = 17;
const long long INF = (long long)1e9 + 7;
long long N;
long long h[maxn];
long long sum[maxn << 1], cnt[maxn << 1];
struct node {
long long x, v;
} a[maxn];
bool cmp(const node& a, const node& b) { return a.x < b.x; }
inline long long lowerbit(long long x) { return x & -x; }
void updata(long long x, long long val, long long tree[]) {
while (x <= N) {
tree[x] += val;
x += lowerbit(x);
}
}
long long query(long long x, long long tree[]) {
long long sum = 0;
while (x > 0) {
sum += tree[x];
x -= lowerbit(x);
}
return sum;
}
int main() {
scanf("%lld", &N);
for (long long i = 1; i <= N; i++) {
scanf("%lld", &a[i].x);
}
for (long long i = 1; i <= N; i++) {
scanf("%lld", &a[i].v);
}
sort(a + 1, a + 1 + N, cmp);
long long l = -1e8;
for (long long i = 1; i <= N; i++) {
h[i] = a[i].v;
}
sort(h + 1, h + 1 + N);
long long d = unique(h + 1, h + 1 + N) - h - 1;
long long ans = 0;
for (long long i = 1; i <= N; i++) {
long long x = lower_bound(h + 1, h + 1 + d, a[i].v) - h;
ans += (query(x, cnt) * (a[i].x - l) - query(x, sum));
updata(x, 1, cnt);
updata(x, a[i].x - l, sum);
}
cout << ans << endl;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(), "Main", 1 << 26).start();
}
long modPow(long a, long p, long m) {
if (a == 1) return 1;
long ans = 1;
while (p > 0) {
if (p % 2 == 1) ans = (ans * a) % m;
a = (a * a) % m;
p >>= 1;
}
return ans;
}
long modInv(long a, long m) {
return modPow(a, m - 2, m);
}
long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
class DSU {
int par[], size[], connectedComponent;
DSU(int n) {
par = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
size[i] = 1;
par[i] = i;
}
connectedComponent = n;
}
int root(int n) {
if (n == par[n]) return n;
return par[n] = root(par[n]);
}
boolean union(int u, int v) {
return f_union(root(u), root(v));
}
boolean f_union(int u, int v) {
if (u == v) return false;
if (size[u] > size[v]) {
size[u] += size[v];
par[v] = u;
} else {
size[v] += size[u];
par[u] = v;
}
connectedComponent--;
return true;
}
DSU clone_DSU() {
DSU t = new DSU(par.length);
t.connectedComponent = connectedComponent;
for (int i = 0; i < par.length; i++) {
t.par[i] = par[i];
t.size[i] = size[i];
}
return t;
}
}
//taken from KharYusuf
static class LCA {
public int[][] par;
public int[] lvl;
public final int LOG;
public final int n;
public ArrayList<Integer>[] a;
public LCA(int n, ArrayList<Integer>[] aa) {
a = aa;
this.n = n;
LOG = log2(n) + 1;
par = new int[n][LOG];
lvl = new int[n];
}
public void build(int u) {
dfs(u, -1, 0);
for (int j = 1; j < LOG; j++)
for (int i = 0; i < n; i++) {
par[i][j] = -1;
if (par[i][j - 1] != -1) par[i][j] = par[par[i][j - 1]][j - 1];
}
}
public void dfs(int cur, int p, int l) {
par[cur][0] = p;
lvl[cur] = l;
for (int i : a[cur]) if (i != p) dfs(i, cur, l + 1);
}
public int query(int u, int v) {
if (lvl[u] < lvl[v]) {
int t = u;
u = v;
v = t;
}
int dis = lvl[u] - lvl[v];
while (dis > 0) {
int raise = log2(dis);
u = par[u][raise];
dis ^= 1 << raise;
}
if (u == v) return u;
for (int i = LOG - 1; i >= 0; i--) {
if (par[u][i] != -1 && par[u][i] != par[v][i]) {
u = par[u][i];
v = par[v][i];
}
}
return par[u][0];
}
public int dist(int u, int v) {
return lvl[u] + lvl[v] - (lvl[query(u, v)] << 1);
}
public int log2(int i) {
int cnt = -1;
while (i > 0) {
i >>= 1;
cnt++;
}
return cnt;
}
}
PrintWriter out;
InputReader sc;
public void run() {
sc = new InputReader(System.in);
// Scanner sc=new Scanner(System.in);
// Random sc=new Random();
out = new PrintWriter(System.out);
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
ArrayList<Integer> temp=new ArrayList();
for (int i = 0; i <n ; i++) {
a[i]=sc.nextInt();
}
for (int i = 0; i <n ; i++) {
b[i]=sc.nextInt();
temp.add(b[i]);
}
Collections.sort(temp);
HashMap<Integer,Integer> map=new HashMap<>();
int counter=0;
for (int i = 0; i <n ; i++) {
if(!map.containsKey(temp.get(i))){
map.put(temp.get(i),counter++);
}
}
Node c[]=new Node[n];
for (int i = 0; i <n ; i++) {
c[i]=new Node(a[i],b[i]);
}
Arrays.sort(c, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return Integer.compare(o2.a,o1.a);
}
});
// for(int key:map.keySet()){
//// out.println(key+" "+map.get(ke));
// }
long ans=0;
tree=new segNode[4*counter];
for (int i = 0; i <4*counter ; i++) {
tree[i]=new segNode(0,0);
}
for (int i = 0; i <n ; i++) {
segNode tempNode=query(0,0,counter-1,map.get(c[i].b),counter-1);
ans+=Math.abs(1l*c[i].a*tempNode.fre-tempNode.sum);
update(0,0,counter-1,map.get(c[i].b),c[i].a);
}
out.println(ans);
out.close();
}
class Node{
int a,b;
public Node(int a, int b) {
this.a = a;
this.b = b;
}
}
class segNode{
long sum;
int fre;
public segNode(long sum, int fre) {
this.sum = sum;
this.fre = fre;
}
}
segNode query(int cur,int l,int r,int start,int end){
if(l>end || r<start)return new segNode(0,0);
if(l>=start && r<=end)return tree[cur];
int mid=(l+r)>>1;
segNode p1=query(2*cur+1,l,mid,start,end);
segNode p2=query(2*cur+2,mid+1,r,start,end);
return merge(p1,p2);
}
segNode tree[];
void update(int cur,int l,int r,int ind,int val){
if(l==r){
tree[cur].fre++;
tree[cur].sum+=val;
return;
}
int mid=(l+r)>>1;
if(ind<=mid)update(2*cur+1,l,mid,ind,val);
else update(2*cur+2,mid+1,r,ind,val);
tree[cur]=merge(tree[2*cur+1],tree[2*cur+2]);
}
segNode merge(segNode o1,segNode o2){
return new segNode(o1.sum+o2.sum,o1.fre+o2.fre);
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prem_cse
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
FMovingPoints.Pair[] p = new FMovingPoints.Pair[n];
TreeSet<Integer> set = new TreeSet<>();
for (int i = 0; i < n; i++) {
p[i] = new FMovingPoints.Pair(a[i], sc.nextInt());
set.add(p[i].s);
}
Arrays.sort(p, (x, y) -> x.v - y.v);
set.add((int) -1e9);
set.add((int) 1e9);
TreeMap<Integer, Integer> map = new TreeMap<>();
while (!set.isEmpty()) map.put(set.pollFirst(), map.size());
FMovingPoints.FenwickTree count = new FMovingPoints.FenwickTree(map.size());
FMovingPoints.FenwickTree sum = new FMovingPoints.FenwickTree(map.size());
long ans = 0;
for (int i = 0; i < n; i++) {
int val = map.get(p[i].s);
long c = count.query(val);
ans += c * p[i].v - sum.query(val);
count.update(val, 1);
sum.update(val, p[i].v);
}
out.println(ans);
}
static class Pair {
int v;
int s;
public Pair(int v, int s) {
this.v = v;
this.s = s;
}
}
static class FenwickTree {
int n;
long[] ft;
FenwickTree(int size) {
n = size;
ft = new long[n + 1];
}
long query(int b) {
long sum = 0;
while (b > 0) {
sum += ft[b];
b -= b & -b;
}
return sum;
}
void update(int k, int val) {
while (k <= n) {
ft[k] += val;
k += k & -k;
}
}
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream), 32768);
st = null;
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
const int MOD = 1e9 + 7;
template <class T>
bool umin(T& a, T b) {
if (a > b) {
a = b;
return 1;
}
return 0;
}
template <class T>
bool umax(T& a, T b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T>
bool umod(T& a) {
while (a < 0) a += MOD;
a %= MOD;
return 1;
}
int n, cn, a[N], b[N], c[N];
long long T[N << 2], S[N << 2], ans;
map<int, int> mk;
pair<int, int> p[N];
void upd(int x, int val, int l, int r, int v) {
S[v]++, T[v] += val;
if (l == r) return;
if (x <= ((l + r) >> 1))
upd(x, val, l, ((l + r) >> 1), v << 1);
else
upd(x, val, ((l + r) >> 1) + 1, r, v << 1 | 1);
}
long long getT(int x, int y, int l, int r, int v) {
if (y < l || r < x) return 0LL;
if (x <= l && r <= y) return T[v];
return getT(x, y, l, ((l + r) >> 1), v << 1) +
getT(x, y, ((l + r) >> 1) + 1, r, v << 1 | 1);
}
long long getS(int x, int y, int l, int r, int v) {
if (y < l || r < x) return 0LL;
if (x <= l && r <= y) return S[v];
return getS(x, y, l, ((l + r) >> 1), v << 1) +
getS(x, y, ((l + r) >> 1) + 1, r, v << 1 | 1);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", a + i);
for (int i = 1; i <= n; i++) scanf("%d", b + i), mk[b[i]] = 1;
for (__typeof(mk.begin()) i = (mk.begin()); i != (mk.end()); i++)
i->second = ++cn;
for (int i = 1; i <= n; i++) {
c[i] = mk[b[i]];
p[i] = {a[i], i};
}
sort(p + 1, p + n + 1);
for (int i = 1; i <= n; i++) {
long long s, t;
ans += (1LL * (s = getS(1, c[p[i].second], 1, cn, 1)) * p[i].first) -
(t = getT(1, c[p[i].second], 1, cn, 1));
upd(c[p[i].second], p[i].first, 1, cn, 1);
}
printf("%lld\n", ans);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct tree {
tree* l;
tree* r;
long long sum;
long long cnt;
tree() {
l = r = nullptr;
sum = cnt = 0;
}
}* rt = new tree;
tree* get_l(tree* v) {
if (!v->l) {
v->l = new tree;
}
return v->l;
}
tree* get_r(tree* v) {
if (!v->r) {
v->r = new tree;
}
return v->r;
}
void add(tree* v, long long l, long long r, long long V, long long x) {
v->cnt++;
v->sum += x;
if (l == r - 1) {
return;
}
long long m = (l + r) / 2;
if (V < m)
add(get_l(v), l, m, V, x);
else
add(get_r(v), m, r, V, x);
}
pair<long long, long long> get_sum(tree* v, long long l, long long r,
long long L, long long R) {
if (r <= L || l >= R) return {0, 0};
if (L <= l && r <= R) return {v->sum, v->cnt};
long long m = (l + r) / 2;
pair<long long, long long> t1 = get_sum(get_l(v), l, m, L, R);
pair<long long, long long> t2 = get_sum(get_r(v), m, r, L, R);
return {t1.first + t2.first, t1.second + t2.second};
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long n;
cin >> n;
vector<pair<long long, long long>> xv(n);
for (long long i = 0; i < n; ++i) {
cin >> xv[i].first;
}
for (long long i = 0; i < n; ++i) {
cin >> xv[i].second;
xv[i].second += 1e8;
}
long long MX_V = 2e8 + 10;
sort(xv.begin(), xv.end());
long long res = 0;
for (long long i = 0; i < n; ++i) {
pair<long long, long long> k = get_sum(rt, 0, MX_V, 0, xv[i].second + 1);
res += xv[i].first * k.second - k.first;
add(rt, 0, MX_V, xv[i].second, xv[i].first);
}
cout << res << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_SIZE = 200010;
pair<int, int> arr[MAX_SIZE], backup[MAX_SIZE];
long long prefix[MAX_SIZE];
int N;
void sortX(int l, int r) {
if (l >= r) return;
int mi = (l + r) / 2;
sortX(l, mi);
sortX(mi + 1, r);
int i = l, j = mi + 1, k = l;
while (i <= mi && j <= r) {
if (arr[i] < arr[j]) {
backup[k++] = arr[i++];
} else {
backup[k++] = arr[j++];
}
}
while (i <= mi) {
backup[k++] = arr[i++];
}
while (j <= r) {
backup[k++] = arr[j++];
}
for (int i = l; i <= r; i++) {
arr[i] = backup[i];
}
}
int lowerBound(int l, int r, int val) {
while (l <= r) {
int mi = (l + r) / 2;
if (arr[mi].second <= val) {
l = mi + 1;
} else {
r = mi - 1;
}
}
int mi = (l + r) / 2;
if (mi >= l && arr[mi].second > val) return mi - 1;
return mi;
}
long long mergeSortV(int l, int r) {
if (l >= r) return 0;
int mi = (l + r) / 2;
long long left = mergeSortV(l, mi);
long long right = mergeSortV(mi + 1, r);
long long mix = 0LL;
prefix[l] = 0LL;
for (int i = l; i <= mi; i++) {
prefix[i + 1] = prefix[i] + (long long)arr[i].first;
}
for (int i = mi + 1; i <= r; i++) {
int pos = lowerBound(l, mi, arr[i].second);
long long cnt = pos - l + 1;
mix += ((long long)arr[i].first * cnt - (prefix[pos + 1] - prefix[l]));
}
int i = l, j = mi + 1, k = l;
while (i <= mi && j <= r) {
if (arr[i].second < arr[j].second) {
backup[k++] = arr[i++];
} else {
backup[k++] = arr[j++];
}
}
while (i <= mi) {
backup[k++] = arr[i++];
}
while (j <= r) {
backup[k++] = arr[j++];
}
for (i = l; i <= r; i++) {
arr[i] = backup[i];
}
return left + right + mix;
}
long long solveBruteforce() {
long long sum = 0LL;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
if (arr[i].second > arr[j].second) {
sum += (long long)max(arr[i].first - arr[j].first, 0);
} else if (arr[i].second < arr[j].second) {
sum += (long long)max(arr[j].first - arr[i].first, 0);
} else {
sum += (long long)max(arr[j].first - arr[i].first,
arr[i].first - arr[j].first);
}
}
}
return sum;
}
int main() {
cin >> N;
for (int i = 0; i < N; i++) {
int x;
cin >> x;
arr[i].first = x;
}
for (int i = 0; i < N; i++) {
int v;
cin >> v;
arr[i].second = v;
}
sortX(0, N - 1);
cout << mergeSortV(0, N - 1) << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.util.Arrays;
import java.util.Scanner;
import java.util.Comparator;
public class MovingPoints {
private static long sumaj(long[] arr,int index) {
long result=0;
while (index>=0) {
result+=arr[index];
index=(index&(index+1))-1;
}
return result;
}
private static void apdejt (long[] t,int index,int vv) {
while (index<t.length) {
t[index]+=vv;
index=index|(index + 1);
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[][] pm=new int[n][2];
int[][] vm=new int[n][2];
for (int i=0;i<n;i++)
pm[i][0]=in.nextInt();
for (int i=0;i<n;i++) {
pm[i][1]=in.nextInt();
vm[i][0]=pm[i][1];
vm[i][1]=i;
}
in.close();
Arrays.sort(vm, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
int nss=0;
int[][] finar=new int[n][2];
for (int i=0;i<n;i++) {
if (i>0 && vm[i][0]!=vm[i-1][0])
nss++;
finar[i][0]=nss;
finar[i][1]=vm[i][1];
}
Arrays.sort(finar,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[1]-b[1];
}});
for (int i=0; i<n;i++) {
pm[i][1] = finar[i][0];
}
Arrays.sort(pm,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[0]-b[0];
}});
long[] c=new long[n];
long[] pts=new long[n];
long totalsum=0;
for (int i=0;i<n;i++) {
int index=pm[i][1];
totalsum+=sumaj(pts,index)*pm[i][0]-sumaj(c,index);
apdejt(pts,index,1);
//System.out.println();
//System.out.println(totalsum);
//System.out.println();
//System.out.println("coordtsum");
//for (int j=0;j<c.length;j++) {
//System.out.print(c[j]);
//}
apdejt(c, index, pm[i][0]);
//System.out.println();
//System.out.println("pointsum");
//for (int j=0;j<pts.length;j++) {
//System.out.print(pts[j]);
//}
}
//System.out.println();
System.out.println(totalsum);
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
int xx[200000], vv[200000];
int compare_v(const void *a, const void *b) {
int i = *(int *)a;
int j = *(int *)b;
return vv[i] - vv[j];
}
int compare_x(const void *a, const void *b) {
int i = *(int *)a;
int j = *(int *)b;
return xx[i] - xx[j];
}
void sort(int *ii, int n, int (*compare)(const void *, const void *)) {
qsort(ii, n, sizeof *ii, compare);
}
void update(long long *ft, int i, int n, int x) {
while (i < n) {
ft[i] += x;
i |= i + 1;
}
}
long long query(long long *ft, int i) {
long long x = 0;
while (i >= 0) {
x += ft[i];
i &= i + 1, i--;
}
return x;
}
int main() {
static long long ft_cnt[200000], ft_sum[200000];
static int ii[200000];
int n, n_, i;
long long ans;
scanf("%d", &n);
for (i = 0; i < n; i++) scanf("%d", &xx[i]);
for (i = 0; i < n; i++) scanf("%d", &vv[i]);
for (i = 0; i < n; i++) ii[i] = i;
sort(ii, n, compare_v);
n_ = 0;
for (i = 0; i < n; i++)
vv[ii[i]] = i + 1 == n || vv[ii[i + 1]] != vv[ii[i]] ? n_++ : n_;
sort(ii, n, compare_x);
ans = 0;
for (i = 0; i < n; i++) {
int i_ = ii[i], x = xx[i_], v = vv[i_];
ans += query(ft_cnt, v) * x - query(ft_sum, v);
update(ft_cnt, v, n_, 1);
update(ft_sum, v, n_, x);
}
printf("%lld\n", ans);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
import sys
input = sys.stdin.readline
from collections import defaultdict
def compress(l):
l = list(set(l))
l.sort()
idx = defaultdict(int)
c = 0
for li in l:
idx[li] = c
c += 1
return idx
class BIT:
#n:要素数
def __init__(self, n):
self.n = n
self.bit = [0]*(n+1)
#i番目(0-indexed)の値にxを足す
def add(self, i, x):
i += 1
while i<=self.n:
self.bit[i] += x
i += i&(-i)
#0からi番目までの値の和を求める
def acc(self, i):
i += 1
s = 0
while i>0:
s += self.bit[i]
i -= i&(-i)
return s
n = int(input())
x = list(map(int, input().split()))
v = list(map(int, input().split()))
xv = [(xi, vi) for xi, vi in zip(x, v)]
xv.sort(key=lambda t: t[0])
idx = compress(v)
sum_bit = BIT(len(idx))
cnt_bit = BIT(len(idx))
ans = 0
for xi, vi in xv:
ans += cnt_bit.acc(idx[vi])*xi-sum_bit.acc(idx[vi])
sum_bit.add(idx[vi], xi)
cnt_bit.add(idx[vi], 1)
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 1000;
const long long M = 1e5 + 10;
const long long inf = 1e9 + 7;
const long long Mod = 1e9 + 7;
const double eps = 1e-6;
int T;
pair<int, int> a[N];
int b[N];
int n;
pair<long long, long long> bt[N];
pair<long long, long long> query(int first) {
pair<long long, long long> res{0, 0};
while (first) {
res.first += bt[first].first;
res.second += bt[first].second;
first -= ((first) & (-first));
}
return res;
}
void modify(int first, int val) {
while (first <= n) {
bt[first].first += val;
bt[first].second++;
first += ((first) & (-first));
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i].first);
}
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i].second);
b[i] = a[i].second;
}
sort(a + 1, a + n + 1);
sort(b + 1, b + n + 1);
int len = unique(b + 1, b + n + 1) - b - 1;
long long ans = 0;
for (int i = 1; i <= n; ++i) {
int id = lower_bound(b + 1, b + len + 1, a[i].second) - b;
pair<long long, long long> cur = query(id);
ans -= cur.first - cur.second * a[i].first;
modify(id, a[i].first);
}
printf("%lld", ans);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct treap {
treap* l = nullptr;
treap* r = nullptr;
long long int pos;
long long int vel;
long long int y;
long long int sum;
int ch;
static long long int s(treap* A) {
if (A == nullptr) return 0;
return A->sum;
}
static int c(treap* A) {
if (A == nullptr) return 0;
return A->ch;
}
static void re(treap* A) {
if (A == nullptr) return;
A->sum = s(A->l) + s(A->r) + A->pos;
A->ch = c(A->l) + c(A->r) + 1;
}
treap(long long int pos, long long int vel) {
this->vel = vel;
this->pos = pos;
this->y = rand() % 1000000000;
re(this);
}
static treap* merge(treap* A, treap* B) {
if (A == nullptr) return B;
if (B == nullptr) return A;
if (A->y > B->y) {
A->r = merge(A->r, B);
re(A);
return A;
} else {
B->l = merge(A, B->l);
re(B);
return B;
}
}
static pair<treap*, treap*> split(treap* A, long long int x) {
if (A == nullptr) return {nullptr, nullptr};
if (A->vel <= x) {
auto T1 = split(A->r, x);
A->r = T1.first;
re(A);
return {A, T1.second};
} else {
auto T1 = split(A->l, x);
A->l = T1.second;
re(A);
return {T1.first, A};
}
}
static treap* insert(treap* A, long long int pos, long long int vel) {
auto T1 = split(A, vel);
auto T2 = merge(T1.first, new treap(pos, vel));
return merge(T2, T1.second);
}
static void func(treap* A, long long int x, long long int& cnt,
long long int& sum) {
auto T1 = split(A, x);
cnt = c(T1.first);
sum = s(T1.first);
merge(T1.first, T1.second);
}
};
const int le = 2 * 1e5;
struct point {
long long int pos = 0;
long long int vel = 0;
point(int pos = 0, int vel = 0) {
this->pos = pos;
this->vel = vel;
}
bool operator<(const point& other) const { return this->pos < other.pos; }
};
point arr[le];
int main() {
iostream::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
srand(time(0));
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i].pos;
}
for (int i = 0; i < n; i++) {
cin >> arr[i].vel;
}
sort(arr, arr + n);
long long int ans = 0;
treap* cur = nullptr;
for (int i = 0; i < n; i++) {
long long int cnt, sum;
treap::func(cur, arr[i].vel, cnt, sum);
cur = treap::insert(cur, arr[i].pos, arr[i].vel);
ans += cnt * arr[i].pos - sum;
}
cout << ans << '\n';
;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct Node {
int X, V;
inline friend bool operator<(Node x, Node y) {
if (x.V == y.V) {
return x.X < y.X;
}
return x.V < y.V;
}
} p[200000];
map<int, int> A;
set<int> B;
int ct;
long long c1[200001];
int c2[200001];
inline void Add(int x, int d) {
for (register int i = x; i <= ct; i += i & -i) {
c1[i] += d;
c2[i]++;
}
}
inline pair<long long, int> Get(int x) {
int s2 = 0;
long long s1 = 0;
for (register int i = x; i != 0; i -= i & -i) {
s1 += c1[i];
s2 += c2[i];
}
return make_pair(s1, s2);
}
int main() {
int n, k;
scanf("%d", &n);
for (register int i = 0; i != n; i++) {
scanf("%d", &p[i].X);
B.insert(p[i].X);
}
for (register int i = 0; i != n; i++) {
scanf("%d", &p[i].V);
}
sort(p, p + n);
for (set<int>::iterator T = B.begin(); T != B.end(); T++) {
ct++;
A[*T] = ct;
}
long long ans = 0;
for (register int i = 0; i != n; i++) {
k = A[p[i].X];
pair<long long, int> Tem = Get(k);
ans += (long long)p[i].X * Tem.second - Tem.first;
Add(k, p[i].X);
}
printf("%lld", ans);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long n, m, ans[200005 << 2], tag[200005 << 2], cnt[200005 << 2],
tagg[200005 << 2];
struct p {
long long x, v, vv;
} a[200005];
int cmp(p a, p b) { return a.v < b.v; }
int cmpp(p a, p b) { return a.x < b.x; }
inline long long ls(long long x) { return x << 1; }
inline long long rs(long long x) { return x << 1 | 1; }
inline void push_up(long long p) {
cnt[p] = cnt[ls(p)] + cnt[rs(p)];
ans[p] = ans[ls(p)] + ans[rs(p)];
}
void build(long long p, long long l, long long r) {
tag[p] = 0;
if (l == r) {
ans[p] = 0;
return;
}
long long mid = (l + r) >> 1;
build(ls(p), l, mid);
build(rs(p), mid + 1, r);
push_up(p);
}
inline void f(long long p, long long l, long long r, long long k) {
tag[p] = tag[p] + k;
ans[p] = ans[p] + k * (r - l + 1);
}
inline void push_down(long long p, long long l, long long r) {
long long mid = (l + r) >> 1;
f(ls(p), l, mid, tag[p]);
f(rs(p), mid + 1, r, tag[p]);
tag[p] = 0;
}
inline void update(long long nl, long long nr, long long l, long long r,
long long p, long long k) {
if (nl <= l && r <= nr) {
ans[p] += k * (r - l + 1);
tag[p] += k;
cnt[p]++;
return;
}
push_down(p, l, r);
long long mid = (l + r) >> 1;
if (nl <= mid) update(nl, nr, l, mid, ls(p), k);
if (nr > mid) update(nl, nr, mid + 1, r, rs(p), k);
push_up(p);
}
long long query(long long q_x, long long q_y, long long l, long long r,
long long p) {
long long res = 0;
if (q_x <= l && r <= q_y) return ans[p];
long long mid = (l + r) >> 1;
push_down(p, l, r);
if (q_x <= mid) res += query(q_x, q_y, l, mid, ls(p));
if (q_y > mid) res += query(q_x, q_y, mid + 1, r, rs(p));
return res;
}
long long query2(long long q_x, long long q_y, long long l, long long r,
long long p) {
long long res = 0;
if (q_x <= l && r <= q_y) return cnt[p];
long long mid = (l + r) >> 1;
push_down(p, l, r);
if (q_x <= mid) res += query2(q_x, q_y, l, mid, ls(p));
if (q_y > mid) res += query2(q_x, q_y, mid + 1, r, rs(p));
return res;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i].x);
}
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i].v);
}
build(1, 1, n);
sort(a + 1, a + 1 + n, cmp);
long long tmp = 1;
a[1].vv = 1;
for (int i = 2; i <= n; i++) {
if (a[i].v != a[i - 1].v) tmp++;
a[i].vv = tmp;
}
long long ans = 0;
sort(a + 1, a + 1 + n, cmpp);
vector<long long> v;
for (int i = 1; i <= n; i++) {
long long tmpp = query(1, a[i].vv, 1, n, 1);
long long cntt = query2(1, a[i].vv, 1, n, 1);
ans += a[i].x * cntt - tmpp;
update(a[i].vv, a[i].vv, 1, n, 1, a[i].x);
}
cout << ans;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author KharYusuf
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
public void solve(int testNumber, FastReader s, PrintWriter w) {
int n = s.nextInt(), MX = (int) 1e8;
int[][] x = new int[n][2];
for (int i = 0; i < n; i++) x[i][0] = s.nextInt();
TreeSet<Integer> p = new TreeSet<>(), ne = new TreeSet<>();
TreeMap<Integer, Integer> po = new TreeMap<>(), nee = new TreeMap<>();
for (int i = 0; i < n; i++) {
x[i][1] = s.nextInt();
if (x[i][1] > 0) p.add(x[i][1]);
else if (x[i][1] < 0) ne.add(x[i][1] + MX);
}
int cnt = 0;
for (int i : p) po.put(i, cnt++);
cnt = 0;
for (int i : ne) nee.put(i, cnt++);
func.sortbyColumn(x, 0);
long ans = 0, cntneg = 0, cntz = 0, cneg = 0, cz = 0;
bit pos = new bit(p.size()), neg = new bit(nee.size()), poscnt = new bit(p.size()), negcnt = new bit(nee.size());
for (int i = 0; i < n; i++) {
if (x[i][1] > 0) {
ans += x[i][0] * cntneg - cneg;
ans += x[i][0] * cntz - cz;
int cur = po.get(x[i][1]);
ans += poscnt.query(cur) * x[i][0] - pos.query(cur);
poscnt.modify(cur, 1);
pos.modify(cur, x[i][0]);
} else if (x[i][1] < 0) {
cntneg++;
cneg += x[i][0];
int cur = nee.get(MX + x[i][1]);
ans += negcnt.query(cur) * x[i][0] - neg.query(cur);
negcnt.modify(cur, 1);
neg.modify(cur, x[i][0]);
} else {
cntz++;
cz += x[i][0];
ans += x[i][0] * cntneg - cneg;
ans += x[i][0] * cntz - cz;
}
}
w.println(ans);
}
public class bit {
public int n;
public long[] t;
public bit(int n) {
t = new long[n];
this.n = n;
}
public void modify(int ind, long val) {
for (; ind < n; ind = ind | (++ind)) t[ind] += val;
}
public long query(int ind) {
long sum = 0;
for (; ind >= 0; ind = (ind & (++ind)) - 1) sum += t[ind];
return sum;
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class func {
public static void sortbyColumn(int[][] arr, final int col) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(final int[] entry1, final int[] entry2) {
if (entry1[col] > entry2[col]) return 1;
if (entry1[col] < entry2[col]) return -1;
return 0;
}
});
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.TreeMap;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
int n;
PrintWriter out;
InputReader in;
final Comparator<Entity> com = new Comparator<Entity>() {
public int compare(Entity x, Entity y) {
int xx = Integer.compare(x.a, y.a);
return xx;
}
};
public void solve(int testNumber, InputReader in, PrintWriter out) {
int t, i, j, tt, k;
this.out = out;
this.in = in;
n = in.nextInt();
Entity en[] = new Entity[n];
TreeSet<Long> ts = new TreeSet<>();
for (i = 0; i < n; i++) {
en[i] = new Entity(in.nextInt(), 0);
}
for (i = 0; i < n; i++) {
en[i].b = in.nextInt();
ts.add(en[i].b);
}
Arrays.sort(en, com);
TreeMap<Long, Integer> tm = new TreeMap<>();
int cc = 0;
for (Long it : ts) {
tm.put(it, cc);
cc++;
}
SegmenTree sg = new SegmenTree();
SegmenTree count = new SegmenTree();
sg.build(cc);
count.build(cc);
long ans = 0;
long ss = 0;
for (i = 0; i < n; i++) {
ans += (i - count.query(tm.get(en[i].b) + 1, cc)) * en[i].a - (ss - sg.query(tm.get(en[i].b) + 1, cc));
count.updateTreeNode(tm.get(en[i].b), 1);
sg.updateTreeNode(tm.get(en[i].b), en[i].a);
ss += en[i].a;
}
pn(ans);
}
void pn(long a) {
out.println(a);
}
class SegmenTree {
int n;
long[] tree;
void build(int x) {
n = x;
tree = new long[2 * n + 1];
}
void updateTreeNode(int p, long value) {
tree[p + n] += value;
p = p + n;
for (int i = p; i > 1; i >>= 1)
tree[i >> 1] = tree[i] + tree[i ^ 1];
}
long query(int l, int r) {
long res = 0;
for (l += n, r += n; l < r;
l >>= 1, r >>= 1) {
if ((l & 1) > 0)
res += tree[l++];
if ((r & 1) > 0)
res += tree[--r];
}
return res;
}
}
class Entity {
int a;
long b;
Entity(int p, int q) {
a = p;
b = q;
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new UnknownError();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct data {
long long x, v, pos;
} p[200005];
struct seg {
long long val, cnt;
} f[1000005];
long n;
bool cmp(data a, data b) {
if (a.v == b.v)
return a.x < b.x;
else
return a.v < b.v;
}
bool cmp2(data a, data b) { return a.x < b.x; }
void update(long id, long l, long r, long u, long long k) {
if (l > u || r < u) return;
if (l == r) {
f[id].val = k;
f[id].cnt = 1;
return;
}
long mid = (l + r) >> 1;
update(id * 2, l, mid, u, k);
update(id * 2 + 1, mid + 1, r, u, k);
f[id].val = f[id * 2].val + f[id * 2 + 1].val;
f[id].cnt = f[id * 2].cnt + f[id * 2 + 1].cnt;
}
seg get(long id, long l, long r, long u, long v) {
if (l > v || r < u) return {0, 0};
if (l >= u && r <= v) return f[id];
long mid = (l + r) >> 1;
seg res, res1, res2;
res1 = get(id * 2, l, mid, u, v);
res2 = get(id * 2 + 1, mid + 1, r, u, v);
res.val = res1.val + res2.val;
res.cnt = res1.cnt + res2.cnt;
return res;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (long i = 1; i <= n; i++) cin >> p[i].x;
for (long i = 1; i <= n; i++) cin >> p[i].v;
sort(p + 1, p + n + 1, cmp);
for (long i = 1; i <= n; i++) p[i].pos = i;
sort(p + 1, p + n + 1, cmp2);
long long res = 0;
for (long i = 1; i <= n; i++) {
seg tmp = get(1, 1, n, 1, p[i].pos - 1);
res += p[i].x * tmp.cnt - tmp.val;
update(1, 1, n, p[i].pos, p[i].x);
}
cout << res;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int p[][]=new int[n][2];
for(int i=0;i<n;i++)
{
p[i][0]=input.nextInt();
}
int v[]=new int[n];
HashSet<Integer> set=new HashSet<>();
for(int i=0;i<n;i++)
{
p[i][1]=input.nextInt();
v[i]=p[i][1];
}
mergeSort(p,0,n-1);
mergeSort(v,0,n-1);
long xs[]=new long[n+1];
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n;i++)
{
map.put(v[i],(i+1));
}
long cnt[]=new long[n+1];
long ans=0;
for(int i=0;i<n;i++)
{
int ve=p[i][1];
int in=map.get(ve);
long sum=sum(xs,in);
long count=sum(cnt,in);
long val=p[i][0]*count-sum;
ans+=val;
update(xs,in,p[i][0],n);
update(cnt,in,1,n);
}
out.println(ans);
}
out.close();
}
public static void mergeSort(int a[],int p,int r)
{
if(p<r)
{
int q=(p+r)/2;
mergeSort(a,p,q);
mergeSort(a,q+1,r);
merge(a,p,q,r);
}
}
public static void merge(int a[],int p,int q,int r)
{
int n1=q-p+2;
int L[]=new int[n1];
int n2=r-q+1;
int R[]=new int[n2];
for(int i=p;i<=q;i++)
{
L[i-p]=a[i];
}
L[n1-1]=Integer.MAX_VALUE;
for(int i=q+1;i<=r;i++)
{
R[i-q-1]=a[i];
}
R[n2-1]=Integer.MAX_VALUE;
int x=0,y=0;
for(int i=p;i<=r;i++)
{
if(L[x]<=R[y])
{
a[i]=L[x];
x++;
}
else
{
a[i]=R[y];
y++;
}
}
}
public static void mergeSort(int a[][],int p,int r)
{
if(p<r)
{
int q=(p+r)/2;
mergeSort(a,p,q);
mergeSort(a,q+1,r);
merge(a,p,q,r);
}
}
public static void merge(int a[][],int p,int q,int r)
{
int n1=q-p+2;
int L[][]=new int[n1][2];
int n2=r-q+1;
int R[][]=new int[n2][2];
for(int i=p;i<=q;i++)
{
L[i-p]=a[i];
}
L[n1-1][0]=Integer.MAX_VALUE;
for(int i=q+1;i<=r;i++)
{
R[i-q-1]=a[i];
}
R[n2-1][0]=Integer.MAX_VALUE;
int x=0,y=0;
for(int i=p;i<=r;i++)
{
if(L[x][0]<=R[y][0])
{
a[i]=L[x];
x++;
}
else
{
a[i]=R[y];
y++;
}
}
}
public static long sum(long xs[],int k)
{
long sum=0;
while(k>0)
{
sum+=xs[k];
k-=k&-k;
}
return sum;
}
public static void update(long xs[],int k,int d,int n)
{
while(k<=n)
{
xs[k]+=d;
k+=k&-k;
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.*;
import java.util.*;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class MovingPoints {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
long mod = (long)(1000000007);
public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException {
while(testNumber-->0){
int n = in.nextInt();
Combine a[] = new Combine[n];
TreeSet<Integer> s = new TreeSet<>();
for(int i=0;i<n;i++)
a[i] = new Combine(in.nextInt() , 0);
for(int i=0;i<n;i++){
a[i].delete = in.nextInt();
s.add(a[i].delete);
}
Arrays.sort(a , new Sort2());
HashMap<Integer , Integer> index = new HashMap<>();
int b = 1;
for(int i:s)
index.put(i , b++);
long count[] = new long[b+1];
long sum[] = new long[b+1];
long ans = 0;
for(int i=0;i<n;i++){
long getCount = get(count , index.get(a[i].delete));
long getSum = get(sum , index.get(a[i].delete));
ans += a[i].value*getCount - getSum;
update(count , index.get(a[i].delete) , 1);
update(sum , index.get(a[i].delete) , a[i].value);
}
out.println(ans);
}
}
public void update(long a[] , int index , long value){
for(int i=index;i<a.length;i += i&(-i))
a[i] += value;
}
public long get(long a[] , int index){
long res = 0;
for(int i=index;i>0;i-=i&(-i))
res += a[i];
return res;
}
public int[] nextGreater(int a[] , int n){
int ng[] = new int[n+1];
Deque<Combine> s = new LinkedList<>();
for(int i=n;i>0;i--){
int k = i;
Combine c = new Combine(a[k] , k);
while(s.size()>0 && s.peekLast().value <= c.value){
Combine d = s.pollLast();
ng[d.delete] = c.delete;
}
s.addLast(c);
}
return ng;
}
public void sieve(int a[]){
a[0] = a[1] = 1;
int i;
for(i=2;i*i<=a.length;i++){
if(a[i] != 0)
continue;
a[i] = i;
for(int k = (i)*(i);k<a.length;k+=i){
if(a[k] != 0)
continue;
a[k] = i;
}
}
}
public int [][] matrixExpo(int c[][] , int n){
int a[][] = new int[c.length][c[0].length];
int b[][] = new int[a.length][a[0].length];
for(int i=0;i<c.length;i++)
for(int j=0;j<c[0].length;j++)
a[i][j] = c[i][j];
for(int i=0;i<a.length;i++)
b[i][i] = 1;
while(n!=1){
if(n%2 == 1){
b = matrixMultiply(a , a);
n--;
}
a = matrixMultiply(a , a);
n/=2;
}
return matrixMultiply(a , b);
}
public int [][] matrixMultiply(int a[][] , int b[][]){
int r1 = a.length;
int c1 = a[0].length;
int c2 = b[0].length;
int c[][] = new int[r1][c2];
for(int i=0;i<r1;i++){
for(int j=0;j<c2;j++){
for(int k=0;k<c1;k++)
c[i][j] += a[i][k]*b[k][j];
}
}
return c;
}
public long nCrPFermet(int n , int r , long p){
if(r==0)
return 1l;
long fact[] = new long[n+1];
fact[0] = 1;
for(int i=1;i<=n;i++)
fact[i] = (i*fact[i-1])%p;
long modInverseR = pow(fact[r] , p-2 , 1l , p);
long modInverseNR = pow(fact[n-r] , p-2 , 1l , p);
long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p;
return w;
}
public long pow(long a , long b , long res , long mod){
if(b==0)
return res;
if(b==1)
return (res*a)%mod;
if(b%2==1){
res *= a;
res %= mod;
b--;
}
// System.out.println(a + " " + b + " " + res);
return pow((a*a)%mod , b/2 , res , mod);
}
public long pow(long a , long b , long res){
if(b == 0)
return res;
if(b==1)
return res*a;
if(b%2==1){
res *= a;
b--;
}
return pow(a*a , b/2 , res);
}
public void swap(int a[] , int p1 , int p2){
int x = a[p1];
a[p1] = a[p2];
a[p2] = x;
}
public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) {
if (start > end) {
return;
}
int mid = (start + end) / 2;
a.add(mid);
sortedArrayToBST(a, start, mid - 1);
sortedArrayToBST(a, mid + 1, end);
}
class Combine{
int value;
int delete;
Combine(int val , int delete){
this.value = val;
this.delete = delete;
}
}
class Sort2 implements Comparator<Combine>{
public int compare(Combine a , Combine b){
if(a.value > b.value)
return 1;
else if(a.value == b.value && a.delete>b.delete)
return 1;
else if(a.value == b.value && a.delete == b.delete)
return 0;
return -1;
}
}
public int lowerLastBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>=x)
return -1;
if(a.get(r)<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid-1)<x)
return mid-1;
else if(a.get(mid)>=x)
r = mid-1;
else if(a.get(mid)<x && a.get(mid+1)>=x)
return mid;
else if(a.get(mid)<x && a.get(mid+1)<x)
l = mid+1;
}
return mid;
}
public int upperFirstBound(ArrayList<Integer> a , Integer x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>x)
return l;
if(a.get(r)<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid+1)>x)
return mid+1;
else if(a.get(mid)<=x)
l = mid+1;
else if(a.get(mid)>x && a.get(mid-1)<=x)
return mid;
else if(a.get(mid)>x && a.get(mid-1)>x)
r = mid-1;
}
return mid;
}
public int lowerLastBound(int a[] , int x){
int l = 0;
int r = a.length-1;
if(a[l]>=x)
return -1;
if(a[r]<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid-1]<x)
return mid-1;
else if(a[mid]>=x)
r = mid-1;
else if(a[mid]<x && a[mid+1]>=x)
return mid;
else if(a[mid]<x && a[mid+1]<x)
l = mid+1;
}
return mid;
}
public int upperFirstBound(long a[] , long x){
int l = 0;
int r = a.length-1;
if(a[l]>x)
return l;
if(a[r]<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid+1]>x)
return mid+1;
else if(a[mid]<=x)
l = mid+1;
else if(a[mid]>x && a[mid-1]<=x)
return mid;
else if(a[mid]>x && a[mid-1]>x)
r = mid-1;
}
return mid;
}
public long log(float number , int base){
return (long) Math.floor((Math.log(number) / Math.log(base)));
}
public long gcd(long a , long b){
if(a<b){
long c = b;
b = a;
a = c;
}
if(b == 0)
return a;
return gcd(b , a%b);
}
public void print2d(long a[][] , PrintWriter out){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
out.print(a[i][j] + " ");
out.println();
}
out.println();
}
public void print1d(int a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
out.println();
}
class Node{
int index;
Node right;
Node left;
public Node(int index){
this.index = index;
right = null;
left = null;
}
}
class AVLTree{
Node root;
public AVLTree(){
this.root = null;
}
public int height(Node n){
return (n == null ? 0 : n.height);
}
public int getBalance(Node n){
return (n == null ? 0 : height(n.left) - height(n.right));
}
public Node rotateRight(Node a){
Node b = a.left;
Node br = b.right;
a.lSum -= b.lSum;
a.lCount -= b.lCount;
b.rSum += a.rSum;
b.rCount += a.rCount;
b.right = a;
a.left = br;
a.height = 1 + Math.max(height(a.left) , height(a.right));
b.height = 1 + Math.max(height(b.left) , height(b.right));
return b;
}
public Node rotateLeft(Node a){
Node b = a.right;
Node bl = b.left;
a.rSum -= b.rSum;
a.rCount -= b.rCount;
b.lSum += a.lSum;
b.lCount += a.lCount;
b.left = a;
a.right = bl;
a.height = 1 + Math.max(height(a.left) , height(a.right));
b.height = 1 + Math.max(height(b.left) , height(b.right));
return b;
}
public Node insert(Node root , long value){
if(root == null){
return new Node(value);
}
if(value<=root.value){
root.lCount++;
root.lSum += value;
root.left = insert(root.left , value);
}
if(value>root.value){
root.rCount++;
root.rSum += value;
root.right = insert(root.right , value);
}
// updating the height of the root
root.height = 1 + Math.max(height(root.left) , height(root.right));
int balance = getBalance(root);
//ll
if(balance>1 && value<=root.left.value)
return rotateRight(root);
//rr
if(balance<-1 && value>root.right.value)
return rotateLeft(root);
//lr
if(balance>1 && value>root.left.value){
root.left = rotateLeft(root.left);
return rotateRight(root);
}
//rl
if(balance<-1 && value<=root.right.value){
root.right = rotateRight(root.right);
return rotateLeft(root);
}
return root;
}
public void insertElement(long value){
this.root = insert(root , value);
}
public int getElementLessThanK(long k){
int count = 0;
Node temp = root;
while(temp!=null){
if(temp.value == k){
if(temp.left == null || temp.left.value<k){
count += temp.lCount;
return count-1;
}
else
temp = temp.left;
}
else if(temp.value>k){
temp = temp.left;
}
else{
count += temp.lCount;
temp = temp.right;
}
}
return count;
}
public void inorder(Node root , PrintWriter out){
Node temp = root;
if(temp!=null){
inorder(temp.left , out);
out.println(temp.value + " " + temp.lCount + " " + temp.rCount);
inorder(temp.right , out);
}
}
class Node{
long value;
long lCount , rCount;
long lSum , rSum;
Node left , right;
int height;
public Node(long value){
this.value = value;
left = null;
right = null;
lCount = 1;
rCount = 1;
lSum = value;
rSum = value;
height = 1;
}
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author KharYusuf
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
public void solve(int testNumber, FastReader s, PrintWriter w) {
int n = s.nextInt(), MX = (int) 1e8;
int[][] x = new int[n][2];
for (int i = 0; i < n; i++) x[i][0] = s.nextInt();
TreeSet<Integer> p = new TreeSet<>(), ne = new TreeSet<>();
TreeMap<Integer, Integer> po = new TreeMap<>(), nee = new TreeMap<>();
for (int i = 0; i < n; i++) {
x[i][1] = s.nextInt();
if (x[i][1] > 0) p.add(x[i][1]);
else if (x[i][1] < 0) ne.add(x[i][1] + MX);
}
int cnt = 0;
for (int i : p) po.put(i, cnt++);
cnt = 0;
for (int i : ne) nee.put(i, cnt++);
func.sortbyColumn(x, 0);
long ans = 0, cntneg = 0, cntz = 0, cneg = 0, cz = 0;
bit pos = new bit(p.size()), neg = new bit(nee.size());
bit poscnt = new bit(p.size()), negcnt = new bit(ne.size());
for (int i = 0; i < n; i++) {
if (x[i][1] > 0) {
ans += x[i][0] * cntneg - cneg;
ans += x[i][0] * cntz - cz;
int cur = po.get(x[i][1]);
ans += poscnt.query(cur) * (long) x[i][0] - pos.query(cur);
poscnt.modify(cur, 1);
pos.modify(cur, x[i][0]);
} else if (x[i][1] < 0) {
cntneg++;
cneg += x[i][0];
int cur = nee.get(MX + x[i][1]);
ans += negcnt.query(cur) * (long) x[i][0] - neg.query(cur);
negcnt.modify(cur, 1);
neg.modify(cur, x[i][0]);
} else {
cntz++;
cz += x[i][0];
ans += x[i][0] * cntneg - cneg;
ans += x[i][0] * cntz - cz;
}
}
w.println(ans);
}
public class bit {
public int n;
public long[] t;
public bit(int n) {
t = new long[n];
this.n = n;
}
public void modify(int ind, long val) {
for (; ind < n; ind = ind | (++ind)) t[ind] += val;
}
public long query(int ind) {
long sum = 0;
for (; ind >= 0; ind = (ind & (++ind)) - 1) sum += t[ind];
return sum;
}
}
}
static class func {
public static void sortbyColumn(int[][] arr, final int col) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(final int[] entry1, final int[] entry2) {
if (entry1[col] > entry2[col]) return 1;
if (entry1[col] < entry2[col]) return -1;
return 0;
}
});
}
}
static class bit {
public int n;
public int[] t;
public bit(int n) {
t = new int[n];
this.n = n;
}
public bit(int[] a, int n) {
t = new int[n];
this.n = n;
for (int i = 0; i < n; i++) {
modify(i, a[i]);
}
}
public void modify(int ind, int val) {
for (; ind < n; ind = ind | (++ind)) t[ind] += val;
}
public int query(int ind) {
int sum = 0;
for (; ind >= 0; ind = (ind & (++ind)) - 1) sum += t[ind];
return sum;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long int MOD = 100000007;
long long int MX = 1000000000;
long long int n;
pair<long long int, long long int> a[200200];
map<long long int, long long int> sor;
map<long long int, long long int> val;
long long int tree[600005];
long long int lazy[600005];
long long int tree1[600005];
long long int lazy1[600005];
void construct(long long int low, long long int high, long long int pos) {
if (low == high) {
tree[pos] = 0;
return;
}
long long int mid = (low + high) / 2;
construct(low, mid, 2 * pos + 1);
construct(mid + 1, high, 2 * pos + 2);
tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2];
}
long long int MRQ(long long int ql, long long int qh, long long int low,
long long int high, long long int pos) {
if (lazy[pos] != 0) {
tree[pos] += lazy[pos] * (high - low + 1);
if (low != high) {
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if (low > qh || high < ql) return 0;
if (ql <= low && qh >= high) return tree[pos];
long long int mid = (low + high) / 2;
return MRQ(ql, qh, low, mid, 2 * pos + 1) +
MRQ(ql, qh, mid + 1, high, 2 * pos + 2);
}
void update(long long int ql, long long int qh, long long int val,
long long int low, long long int high, long long int pos) {
if (lazy[pos] != 0) {
tree[pos] += lazy[pos] * (high - low + 1);
if (low != high) {
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if (low > qh || high < ql) return;
if (ql <= low && qh >= high) {
tree[pos] += val * (high - low + 1);
if (low != high) {
lazy[2 * pos + 1] += val;
lazy[2 * pos + 2] += val;
}
return;
}
long long int mid = (low + high) / 2;
update(ql, qh, val, low, mid, 2 * pos + 1);
update(ql, qh, val, mid + 1, high, 2 * pos + 2);
tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2];
}
void construct1(long long int low, long long int high, long long int pos) {
if (low == high) {
tree1[pos] = 0;
return;
}
long long int mid = (low + high) / 2;
construct1(low, mid, 2 * pos + 1);
construct1(mid + 1, high, 2 * pos + 2);
tree1[pos] = tree1[2 * pos + 1] + tree1[2 * pos + 2];
}
long long int MRQ1(long long int ql, long long int qh, long long int low,
long long int high, long long int pos) {
if (lazy1[pos] != 0) {
tree1[pos] += lazy1[pos] * (high - low + 1);
if (low != high) {
lazy1[2 * pos + 1] += lazy1[pos];
lazy1[2 * pos + 2] += lazy1[pos];
}
lazy1[pos] = 0;
}
if (low > qh || high < ql) return 0;
if (ql <= low && qh >= high) return tree1[pos];
long long int mid = (low + high) / 2;
return MRQ1(ql, qh, low, mid, 2 * pos + 1) +
MRQ1(ql, qh, mid + 1, high, 2 * pos + 2);
}
void update1(long long int ql, long long int qh, long long int val,
long long int low, long long int high, long long int pos) {
if (lazy1[pos] != 0) {
tree1[pos] += lazy1[pos] * (high - low + 1);
if (low != high) {
lazy1[2 * pos + 1] += lazy1[pos];
lazy1[2 * pos + 2] += lazy1[pos];
}
lazy1[pos] = 0;
}
if (low > qh || high < ql) return;
if (ql <= low && qh >= high) {
tree1[pos] += val * (high - low + 1);
if (low != high) {
lazy1[2 * pos + 1] += val;
lazy1[2 * pos + 2] += val;
}
return;
}
long long int mid = (low + high) / 2;
update1(ql, qh, val, low, mid, 2 * pos + 1);
update1(ql, qh, val, mid + 1, high, 2 * pos + 2);
tree1[pos] = tree1[2 * pos + 1] + tree1[2 * pos + 2];
}
int main() {
ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i].first;
for (int i = 1; i <= n; i++) cin >> a[i].second;
for (int i = n; i >= 1; i--) {
sor[a[i].second]++;
}
map<long long int, long long int>::iterator itr;
int cnt = 0;
for (itr = sor.begin(); itr != sor.end(); itr++) {
cnt++;
val[itr->first] = cnt;
}
for (int i = 1; i <= n; i++) a[i].second = val[a[i].second];
sort(a + 1, a + n + 1);
construct(0, n, 0);
construct1(0, n, 0);
long long int res = 0;
for (int i = n; i >= 1; i--) {
res += MRQ(a[i].second, n, 0, n, 0) -
MRQ1(a[i].second, n, 0, n, 0) * a[i].first;
update1(a[i].second, a[i].second, 1, 0, n, 0);
update(a[i].second, a[i].second, a[i].first, 0, n, 0);
}
cout << res << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10, mod = 1e9 + 7, INF = 0x3f3f3f3f;
long long fwk[maxn], cnt[maxn];
void upd(int p, int c) {
for (; p < maxn; p += p & -p) fwk[p] += c, cnt[p]++;
}
void qry(int p, long long& sum, long long& c) {
sum = c = 0;
for (; p; p -= p & -p) sum += fwk[p], c += cnt[p];
}
vector<int> d;
inline int hs(int x) {
return lower_bound(d.begin(), d.end(), x) - d.begin() + 1;
}
pair<int, int> p[maxn];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) scanf("%d", &p[i].first);
for (int i = 1; i <= n; ++i) {
scanf("%d", &p[i].second);
d.push_back(p[i].second);
}
sort(p + 1, p + 1 + n);
sort(d.begin(), d.end());
d.erase(unique(d.begin(), d.end()), d.end());
long long ans = 0, sum, c;
for (int i = 1; i <= n; ++i) {
qry(hs(p[i].second), sum, c);
ans += c * p[i].first - sum;
upd(hs(p[i].second), p[i].first);
}
cout << ans;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
constexpr long long maxN = 2e5 + 43;
long long n;
vector<pair<long long, long long>> point;
vector<long long> val, cnt, cval;
long long LSOne(long long k) { return (k & (-k)); }
void update(vector<long long>& f, long long pos, long long val) {
for (; pos <= n; pos += LSOne(pos)) f[pos] += val;
}
long long rsq(vector<long long>& f, long long pos) {
long long sum = 0;
for (; pos; pos -= LSOne(pos)) sum += f[pos];
return sum;
}
bool Comp(const pair<long long, long long>& a,
const pair<long long, long long>& b) {
return a.first < b.first;
}
signed main() {
ios_base::sync_with_stdio(false);
cin >> n;
point.resize(n + 1);
val.resize(n + 1);
cnt.resize(n + 1);
cval.resize(n + 1);
for (long long i = 1; i <= n; ++i) {
cin >> point[i].first;
}
for (long long i = 1; i <= n; ++i) {
cin >> point[i].second;
val[i] = point[i].second;
}
sort(point.begin() + 1, point.begin() + n + 1);
sort(val.begin() + 1, val.begin() + n + 1);
long long ans = 0;
for (long long i = 1; i <= n; ++i) {
long long pos =
lower_bound(val.begin() + 1, val.begin() + n + 1, point[i].second) -
val.begin();
ans += rsq(cnt, pos) * point[i].first - rsq(cval, pos);
update(cnt, pos, 1);
update(cval, pos, point[i].first);
}
cout << ans;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int MOD = 1000000000 + 7;
long long int inverse(long long int i) {
if (i == 1) return 1;
return (MOD - ((MOD / i) * inverse(MOD % i)) % MOD + MOD) % MOD;
}
long long int calc(vector<pair<long long int, long long int>>& v1, int st,
int fn) {
if (fn - st + 1 <= 1) return 0;
vector<pair<int, int>> temp(fn - st + 1);
int mid = (st + fn) / 2;
long long int r1 = calc(v1, st, mid);
r1 = r1 + calc(v1, mid + 1, fn);
long long int sum3 = 0;
for (int i = mid + 1; i <= fn; ++i) sum3 += v1[i].first;
int j = mid + 1;
for (int i = st; i <= mid; ++i) {
while (j <= fn && v1[j].second < v1[i].second) {
sum3 -= v1[j].first;
j++;
}
r1 = r1 + (sum3 - (fn - j + 1) * v1[i].first);
}
int st1 = st, st2 = mid + 1;
int count1 = 0;
while (st1 <= mid && st2 <= fn) {
if (v1[st1].second <= v1[st2].second) {
temp[count1].first = v1[st1].first;
temp[count1].second = v1[st1].second;
count1++;
st1++;
} else {
temp[count1].first = v1[st2].first;
temp[count1].second = v1[st2].second;
count1++;
st2++;
}
}
for (int i = st1; i <= mid; ++i) {
temp[count1].first = v1[i].first;
temp[count1].second = v1[i].second;
count1++;
}
for (int i = st2; i <= fn; ++i) {
temp[count1].first = v1[i].first;
temp[count1].second = v1[i].second;
count1++;
}
for (int i = st; i <= fn; ++i) {
v1[i].first = temp[i - st].first;
v1[i].second = temp[i - st].second;
}
return r1;
}
int main() {
int n;
cin >> n;
vector<pair<long long int, long long int>> v1, v2;
vector<long long int> temp1, temp2;
long long int x[n], v[n];
for (int i = 0; i < n; ++i) scanf("%lld", x + i);
for (int i = 0; i < n; ++i) scanf("%lld", v + i);
for (int i = 0; i < n; ++i) {
if (v[i] >= 0) {
v1.push_back({x[i], v[i]});
temp1.push_back(x[i]);
} else {
v2.push_back({x[i], v[i]});
temp2.push_back(x[i]);
}
}
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
long long int y = 0;
int n1 = v1.size();
int n2 = v2.size();
y = y + calc(v1, 0, n1 - 1);
y = y + calc(v2, 0, n2 - 1);
sort(temp1.begin(), temp1.end());
sort(temp2.begin(), temp2.end());
int n3 = temp2.size();
long long int sum4 = 0;
int st1 = 0;
for (int i = 0; i < temp1.size(); ++i) {
while (st1 < n3 && temp2[st1] < temp1[i]) {
sum4 += temp2[st1];
st1++;
}
y = y + st1 * temp1[i] - sum4;
}
printf("%lld\n", y);
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pli = pair<ll, int>;
using pii = pair<int, int>;
constexpr ll mod = 1e9 + 7;
constexpr int N = 200010;
struct node {
ll x;
int v, id;
bool operator<(const node &o) const { return x < o.x; }
} q[N];
int n, nn, b[N];
ll fw[2][N];
int lowbit(int x) { return x & -x; }
void update(int op, int k, int x) {
for (; k <= n; k += lowbit(k)) fw[op][k] += x;
}
ll query(int op, int k) {
ll res = 0;
for (; k; k -= lowbit(k)) res += fw[op][k];
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T = 1;
while (T--) {
cin >> n;
for (int i = 1; i <= n; i++) cin >> q[i].x;
for (int i = 1; i <= n; i++) {
cin >> q[i].v;
b[i] = q[i].v;
q[i].id = i;
}
sort(b + 1, b + 1 + n);
nn = unique(b + 1, b + 1 + n) - b - 1;
for (int i = 1; i <= n; i++)
q[i].v = lower_bound(b + 1, b + 1 + nn, q[i].v) - b;
sort(q + 1, q + 1 + n);
ll res = 0;
for (int i = 1; i <= n; i++) {
res += q[i].x * query(0, q[i].v) - query(1, q[i].v);
update(0, q[i].v, 1);
update(1, q[i].v, q[i].x);
}
cout << res << '\n';
}
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python2
|
from sys import stdin
from collections import *
def fast2():
import os, sys, atexit
from cStringIO import StringIO as BytesIO
# range = xrange
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).readline
class order_tree:
def __init__(self, arr):
self.n = len(arr)
self.tree = [[0, 0] for _ in range(self.n * 2)]
self.order = {arr[i]: i for i in range(self.n)}
# get interval[l,r)
def query(self, l):
res, coun = 0, 0
l = self.order[l] + self.n
r = self.n * 2
while l < r:
if l & 1:
res += self.tree[l][0]
coun += self.tree[l][1]
l += 1
if r & 1:
r -= 1
res += self.tree[r][0]
coun += self.tree[r][1]
l >>= 1
r >>= 1
return res, coun
def update(self, ix, val):
ix = self.n + self.order[ix]
# set new value
self.tree[ix][0] += val
self.tree[ix][1] += 1
# move up
while ix > 1:
self.tree[ix >> 1][0] = self.tree[ix][0] + self.tree[ix ^ 1][0]
self.tree[ix >> 1][1] = self.tree[ix][1] + self.tree[ix ^ 1][1]
ix >>= 1
# input = fast2()
rints = lambda: [int(x) for x in stdin.readline().split()]
n, a = int(input()), sorted(map(lambda x, y: [x, y], rints(), rints()))
dis = sorted(set([x[1] for x in a]))
tree, ans = order_tree(dis), 0
for i in range(n - 1, -1, -1):
su, coun = tree.query(a[i][1])
ans += su - coun * a[i][0]
tree.update(a[i][1], a[i][0])
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.util.*;
import java.io.*;
import java.text.*;
public class F1311 {
public static long solve(ArrayList<Pair> arr) {
FenwickTree cnt = new FenwickTree(arr.size());
FenwickTree val = new FenwickTree(arr.size());
TreeSet<Integer> ts = new TreeSet<Integer>();
for (Pair x : arr)
ts.add(x.v);
TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>();
while (!ts.isEmpty()) {
tm.put(ts.pollFirst(), tm.size() + 1);
}
// System.out.println(tm);
Collections.sort(arr, (a, b) -> a.x - b.x);
long sum = 0;
for (Pair p : arr) {
int lim = tm.get(p.v);
if (lim > 0) {
long cntt = cnt.rsq(lim);
long value = val.rsq(lim);
sum += p.x * cntt - value;
}
cnt.point_update(lim, 1);
val.point_update(lim, p.x);
// System.out.println(sum);
}
return sum;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] x = sc.nextIntArr(n);
int[] v = sc.nextIntArr(n);
ArrayList<Pair> r = new ArrayList<Pair>();
for (int i = 0; i < n; i++) {
r.add(new Pair(x[i], v[i]));
}
pw.println(solve(r));
pw.close();
}
static class FenwickTree { // one-based DS
int n;
long[] ft;
FenwickTree(int size) {
n = size;
ft = new long[n + 1];
}
long rsq(int b) // O(log n)
{
long sum = 0;
while (b > 0) {
sum += ft[b];
b -= b & -b;
} // min?
return sum;
}
long rsq(int a, int b) {
return rsq(b) - rsq(a - 1);
}
void point_update(int k, int val) // O(log n), update = increment
{
while (k <= n) {
ft[k] += val;
k += k & -k;
} // min?
}
long point_query(int idx) // c * O(log n), c < 1
{
long sum = ft[idx];
if (idx > 0) {
int z = idx ^ (idx & -idx);
--idx;
while (idx != z) {
sum -= ft[idx];
idx ^= idx & -idx;
}
}
return sum;
}
}
static class Pair {
int x, v;
public Pair(int a, int b) {
x = a;
v = b;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
long startTime = System.currentTimeMillis();
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
System.err.println(System.currentTimeMillis()-startTime+"ms");
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class FMovingPoints {
private final int iinf = 1_000_000_000;
public FMovingPoints() {
}
public static Pair<Long, Long> add(Pair<Long, Long> a, Pair<Long, Long> b) {
return new Pair<>(a.a+b.a, a.b+b.b);
}
public static Pair<Long, Long> subtract(Pair<Long, Long> a, Pair<Long, Long> b) {
return new Pair<>(a.a-b.a, a.b-b.b);
}
public void solve(int kase, InputReader in, Output pw) {
int n = in.nextInt();
int[][] arr = new int[n][2];
for(int i = 0; i<2; i++) {
for(int j = 0; j<n; j++) {
arr[j][i] = in.nextInt();
}
}
Arrays.sort(arr, Comparator.comparingInt(o -> o[1]));
{
int prev = -iinf, ind = -1;
for(int i = 0; i<n; i++) {
if(arr[i][1]!=prev) {
prev = arr[i][1];
arr[i][1] = ++ind;
}else {
arr[i][1] = ind;
}
}
}
Arrays.sort(arr, Comparator.comparingInt(o -> o[0]));
TFenwickTree<Pair<Long, Long>> ft;
{
Pair<Long, Long>[] tmp = new Pair[n];
for(int i = 0; i<n; i++) {
tmp[i] = new Pair<>(0L, 0L);
}
ft = new TFenwickTree<>(tmp, new Pair<>(0L, 0L), FMovingPoints::add, FMovingPoints::subtract);
}
for(int i = 0; i<n; i++) {
ft.set(arr[i][1], add(ft.get(arr[i][1]), new Pair<>((long) arr[i][0]-arr[0][0], 1L)));
}
long sum = 0, ans = 0;
for(int i = 0; i<n; i++) {
ft.set(arr[i][1], subtract(ft.get(arr[i][1]), new Pair<>((long) arr[i][0]-arr[0][0], 1L)));
Utilities.Debug.dbg(ft.arr);
var p = ft.query(arr[i][1], n-1);
ans += p.a-(arr[i][0]-arr[0][0])*p.b;
}
pw.println(ans);
}
}
static class Pair<T1, T2> implements Comparable<Pair<T1, T2>> {
public T1 a;
public T2 b;
public Pair(Pair<T1, T2> p) {
this(p.a, p.b);
}
public Pair(T1 a, T2 b) {
this.a = a;
this.b = b;
}
public String toString() {
return a+" "+b;
}
public int hashCode() {
return Objects.hash(a, b);
}
public boolean equals(Object o) {
if(o instanceof Pair) {
Pair p = (Pair) o;
return a.equals(p.a)&&b.equals(p.b);
}
return false;
}
public int compareTo(Pair<T1, T2> p) {
int cmp = ((Comparable<T1>) a).compareTo(p.a);
if(cmp==0) {
return ((Comparable<T2>) b).compareTo(p.b);
}
return cmp;
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public String lineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
lineSeparator = System.lineSeparator();
}
public void println(long l) {
println(String.valueOf(l));
}
public void println(String s) {
sb.append(s);
println();
}
public void println() {
sb.append(lineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static class FastReader implements InputReader {
final private int BUFFER_SIZE = 1<<16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public FastReader(InputStream is) {
din = new DataInputStream(is);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public int nextInt() {
int ret = 0;
byte c = skipToDigit();
boolean neg = (c=='-');
if(neg) {
c = read();
}
do {
ret = ret*10+c-'0';
} while((c = read())>='0'&&c<='9');
if(neg) {
return -ret;
}
return ret;
}
private boolean isDigit(byte b) {
return b>='0'&&b<='9';
}
private byte skipToDigit() {
byte ret;
while(!isDigit(ret = read())&&ret!='-') ;
return ret;
}
private void fillBuffer() {
try {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}catch(IOException e) {
e.printStackTrace();
throw new InputMismatchException();
}
if(bytesRead==-1) {
buffer[0] = -1;
}
}
private byte read() {
if(bytesRead==-1) {
throw new InputMismatchException();
}else if(bufferPointer==bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
static class Utilities {
public static class Debug {
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) {
if(LOCAL) {
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
}
static class TFenwickTree<T> {
int n;
T initialValue;
public T[] arr;
public T[] value;
BinaryOperator<T> operation;
BinaryOperator<T> undo;
public TFenwickTree(T[] arr, T initialValue, BinaryOperator<T> operation, BinaryOperator<T> undo) {
n = arr.length;
this.initialValue = initialValue;
this.arr = (T[]) new Object[n];
value = (T[]) new Object[n+1];
Arrays.fill(value, initialValue);
Arrays.fill(this.arr, initialValue);
this.operation = operation;
this.undo = undo;
for(int i = 0; i<n; i++) {
set(i, arr[i]);
}
}
public void set(int ind, T val) {
T old = arr[ind];
arr[ind] = val;
ind++;
while(ind<=n) {
value[ind] = operation.apply(undo.apply(value[ind], old), val);
ind += ind&-ind;
}
}
private T psum(int ind) {
T ret = initialValue;
while(ind>0) {
ret = operation.apply(ret, value[ind]);
ind -= ind&-ind;
}
return ret;
}
public T query(int l, int r) {
return undo.apply(psum(r+1), psum(l));
}
public T get(int ind) {
return arr[ind];
}
}
static interface InputReader {
int nextInt();
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int M = 2e5 + 5;
int n, t[M], k;
long long ans;
struct node {
long long p;
int v;
} a[M];
struct BIT {
long long s[M];
void add(int i, long long x) {
for (; i <= k; i += i & -i) s[i] += x;
}
long long ask(int i) {
long long res = 0;
for (; i > 0; i -= i & -i) res += s[i];
return res;
}
} f1, f2;
inline int find(int x) {
int l = 1, r = k, mid;
while (l < r) {
mid = (l + r) >> 1;
if (t[mid] < x)
l = mid + 1;
else
r = mid;
}
return l;
}
int cmp(node x, node y) { return x.p < y.p; }
int main() {
cin >> n;
for (int i = 1; i <= n; i++) scanf("%lld", &a[i].p);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i].v);
t[i] = a[i].v;
}
sort(a + 1, a + n + 1, cmp);
sort(t + 1, t + n + 1);
k++;
for (int i = 2; i <= n; i++)
if (t[i] != t[i - 1]) t[++k] = t[i];
for (int i = 1; i <= n; i++) {
int w = find(a[i].v);
ans += a[i].p * f1.ask(w) - f2.ask(w);
f1.add(w, 1);
f2.add(w, a[i].p);
}
cout << ans << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 1, -1, -1, -1, 1, 1};
int dy[] = {1, -1, 0, 0, -1, 1, 1, -1};
template <class T>
inline T biton(T n, T pos) {
return n | ((T)1 << pos);
}
template <class T>
inline T bitoff(T n, T pos) {
return n & ~((T)1 << pos);
}
template <class T>
inline T ison(T n, T pos) {
return (bool)(n & ((T)1 << pos));
}
template <class T>
inline T gcd(T a, T b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
inline int nxt() {
int aaa;
scanf("%d", &aaa);
return aaa;
}
inline long long lxt() {
long long aaa;
scanf("%lld", &aaa);
return aaa;
}
inline double dxt() {
double aaa;
scanf("%lf", &aaa);
return aaa;
}
template <class T>
inline T bigmod(T p, T e, T m) {
T ret = 1;
for (; e > 0; e >>= 1) {
if (e & 1) ret = (ret * p) % m;
p = (p * p) % m;
}
return (T)ret;
}
class fenwick {
public:
long long tree[200005] = {0};
void Update(int pos, long long val, int limit) {
while (pos <= limit) {
tree[pos] += val;
pos += pos & (-pos);
}
}
long long Query(int pos) {
long long sum = 0;
while (pos > 0) {
sum += tree[pos];
pos -= pos & (-pos);
}
return sum;
}
} past, pastSum;
void solve() {
vector<pair<long long, long long>> v;
int n = nxt();
for (int i = 0; i < n; i++) {
v.emplace_back(lxt(), 0);
}
for (int i = 0; i < n; i++) {
v[i].second = lxt();
}
sort(v.begin(), v.end());
set<long long> st;
for (int i = 0; i < n; i++) st.insert(v[i].second);
vector<long long> velocity(st.begin(), st.end());
n = (int)(velocity).size();
long long ans = 0;
for (int i = 0; i < (int)(v).size(); i++) {
int pos = lower_bound(velocity.begin(), velocity.end(), v[i].second) -
velocity.begin();
ans += past.Query(pos + 1) * v[i].first - pastSum.Query(pos + 1);
past.Update(pos + 1, 1LL, n);
pastSum.Update(pos + 1, v[i].first, n);
}
printf("%lld\n", ans);
}
int main() {
cout.setf(ios::fixed);
cout.precision(10);
int tc = 1;
while (tc--) {
solve();
}
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long bit1[200005], bit2[200005];
inline void upd(long long idx, long long val, long long bit[]) {
while (idx < 200005) {
bit[idx] += val;
idx += (idx & -idx);
}
}
inline long long que(long long idx, long long bit[]) {
long long ans = 0;
while (idx > 0) {
ans += bit[idx];
idx -= (idx & -idx);
}
return ans;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n;
cin >> n;
vector<long long> v;
map<long long, long long> m;
pair<long long, long long> arr[n];
for (long long i = 0; i < n; i++) cin >> arr[i].first;
for (long long i = 0; i < n; i++) {
cin >> arr[i].second;
if (m[arr[i].second] == 0) {
m[arr[i].second]++;
v.push_back(arr[i].second);
}
}
sort(v.begin(), v.end());
sort(arr, arr + n);
for (long long i = 0; i < n; i++) {
long long x = lower_bound(v.begin(), v.end(), arr[i].second) - v.begin();
arr[i].second = x + 1;
}
long long ans = 0;
for (long long i = 0; i < n; i++) {
long long x = que(arr[i].second, bit1), y = que(arr[i].second, bit2);
ans += (x * arr[i].first - y);
upd(arr[i].second, 1, bit1);
upd(arr[i].second, arr[i].first, bit2);
}
cout << ans << '\n';
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long n;
pair<long long, long long> p[200005];
long long v[200005];
map<long long, long long> m;
long long f0[200005];
long long f1[200005];
void up0(long long x, long long val) {
for (long long i = x; i <= 200000; i += i & -i) f0[i] += val;
}
void up1(long long x, long long val) {
for (long long i = x; i <= 200000; i += i & -i) f1[i] += val;
}
long long get0(long long pos) {
long long ans = 0;
for (long long i = pos; i > 0; i -= i & -i) ans += f0[i];
return ans;
}
long long get1(long long pos) {
long long ans = 0;
for (long long i = pos; i > 0; i -= i & -i) ans += f1[i];
return ans;
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (long long i = 1; i <= n; i++) cin >> p[i].first;
for (long long i = 1; i <= n; i++) {
cin >> p[i].second;
v[i] = p[i].second;
}
sort(v + 1, v + 1 + n);
sort(p + 1, p + 1 + n);
long long c = 0;
for (long long i = 1; i <= n; i++) {
if (m[v[i]] == 0) {
m[v[i]] = ++c;
}
}
long long ans = 0;
for (long long i = 1; i <= n; i++) {
long long x = p[i].first;
long long sp = p[i].second;
long long c = get0(m[sp]);
long long cur = get1(m[sp]);
ans += x * c - cur;
up0(m[sp], 1);
up1(m[sp], x);
}
cout << ans;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
int dr[] = {2, 2, -2, -2, 1, -1, 1, -1};
int dc[] = {1, -1, 1, -1, 2, 2, -2, -2};
int dr1[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dc1[] = {1, -1, 1, 0, -1, 0, 1, -1};
int dr2[] = {0, 0, 1, -1};
int dc2[] = {1, -1, 0, 0};
using namespace std;
long long a[200005];
long long dp[200005];
long long tr[2][200005];
void update(long long f, long long x, long long val) {
while (x < 200005) {
tr[f][x] += val;
x += x & (-x);
}
}
long long query(long long f, long long x) {
long long s = 0;
while (x > 0) {
s += tr[f][x];
x -= x & (-x);
}
return s;
}
int main() {
long long n, i, j;
string t;
while (cin >> n) {
for (i = 1; i <= n; i++) cin >> a[i];
vector<pair<long long, long long> > v;
map<long long, long long> mp;
for (i = 1; i <= n; i++) {
long long x;
cin >> x;
v.push_back(make_pair(a[i], x));
mp[x];
}
map<long long, long long>::iterator it;
sort(v.begin(), v.end());
long long cn = 0;
for (it = mp.begin(); it != mp.end(); it++) it->second = ++cn;
long long ans = 0;
reverse(v.begin(), v.end());
for (i = 0; i < v.size(); i++) {
long long p = v[i].first;
long long q = mp[v[i].second];
long long r = query(0, cn) - query(0, q - 1);
long long r1 = query(1, cn) - query(1, q - 1);
update(0, q, 1);
update(1, q, p);
ans += (r1 - p * r);
}
cout << ans << endl;
}
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python2
|
from sys import stdin
from collections import *
def fast2():
import os, sys, atexit
from cStringIO import StringIO as BytesIO
# range = xrange
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).readline
class order_tree:
def __init__(self, arr):
self.n = len(arr)
self.tree = [[0, 0] for _ in range(self.n * 2)]
self.order = defaultdict(int, {arr[i]: i for i in range(self.n)})
# get interval[l,r)
def query(self, l):
res, coun = 0, 0
l = self.order[l] + self.n
r = self.n * 2
while l < r:
if l & 1:
res += self.tree[l][0]
coun += self.tree[l][1]
l += 1
if r & 1:
r -= 1
res += self.tree[r][0]
coun += self.tree[r][1]
l >>= 1
r >>= 1
return res, coun
def update(self, ix, val):
ix = self.n + self.order[ix]
# set new value
self.tree[ix][0] += val
self.tree[ix][1] += 1
# move up
while ix > 1:
self.tree[ix >> 1][0] = self.tree[ix][0] + self.tree[ix ^ 1][0]
self.tree[ix >> 1][1] = self.tree[ix][1] + self.tree[ix ^ 1][1]
ix >>= 1
input = fast2()
rints = lambda: [int(x) for x in input().split()]
n, a = int(input()), sorted(map(lambda x, y: [x, y], rints(), rints()))
dis = sorted(set([x[1] for x in a]))
tree, ans = order_tree(dis), 0
for i in range(n - 1, -1, -1):
su, coun = tree.query(a[i][1])
ans += su - coun * a[i][0]
tree.update(a[i][1], a[i][0])
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int tab_x[200000 + 5];
int tab_v[200000 + 5];
long long D_dist[550000 + 5];
int D_ile[550000 + 5];
int zakresy[550000 + 5][2];
int max_pot = 1;
int QUERRY_ile(int L, int R, int w) {
if (zakresy[w][0] > R || L > zakresy[w][1]) return 0;
if (L <= zakresy[w][0] && zakresy[w][1] <= R) return D_ile[w];
return QUERRY_ile(L, R, w * 2) + QUERRY_ile(L, R, w * 2 + 1);
}
long long QUERRY_dist(int L, int R, int w) {
if (zakresy[w][0] > R || L > zakresy[w][1]) return 0;
if (L <= zakresy[w][0] && zakresy[w][1] <= R) return D_dist[w];
return QUERRY_dist(L, R, w * 2) + QUERRY_dist(L, R, w * 2 + 1);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> tab_x[i];
for (int i = 0; i < n; i++) cin >> tab_v[i];
vector<pair<int, int> > V_0;
for (int i = 0; i < n; i++) V_0.push_back({tab_x[i], tab_v[i]});
sort(V_0.begin(), V_0.end());
for (int i = 0; i < n; i++) {
tab_x[i] = V_0[i].first;
tab_v[i] = V_0[i].second;
}
priority_queue<pair<int, int> > PQ;
for (int i = 0; i < n; i++) PQ.push({-tab_v[i], i});
int last_ = INT_MIN;
int name_num = 0;
while (!PQ.empty()) {
int top_val = -PQ.top().first;
int top_place = PQ.top().second;
PQ.pop();
if (top_val != last_) {
name_num++;
last_ = top_val;
}
tab_v[top_place] = name_num;
}
while (max_pot < name_num) max_pot *= 2;
for (int i = max_pot; i < 2 * max_pot; i++)
zakresy[i][0] = zakresy[i][1] = i - max_pot + 1;
for (int i = max_pot - 1; i >= 1; i--) {
zakresy[i][0] = zakresy[2 * i][0];
zakresy[i][1] = zakresy[2 * i + 1][1];
}
long long RESULT = 0;
for (int i = 0; i < n; i++) {
long long akt_x = tab_x[i];
int akt_v = tab_v[i];
int ile_ = QUERRY_ile(1, akt_v, 1);
long long suma_dist = QUERRY_dist(1, akt_v, 1);
long long bazowy_koszt = ile_;
bazowy_koszt *= akt_x;
bazowy_koszt -= suma_dist;
RESULT += bazowy_koszt;
int w = max_pot + akt_v - 1;
while (w) {
D_ile[w]++;
D_dist[w] += akt_x;
w /= 2;
}
}
cout << RESULT;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
def bitadd(a,w,bit):
x = a
while x <= (len(bit)-1):
bit[x] += w
x += x & (-1 * x)
def bitsum(a,bit):
ret = 0
x = a
while x > 0:
ret += bit[x]
x -= x & (-1 * x)
return ret
n = int(input())
x = list(map(int,input().split()))
v = list(map(int,input().split()))
vlis = []
for i in v:
vlis.append(i)
vlis.sort()
vdic = {}
for i in range(n):
vdic[vlis[i]] = i+1
#print (vdic)
xv = []
for i in range(n):
xv.append([x[i],v[i]])
xv.sort()
ans = 0
BIT = [0] * (n+1)
BIT2 = [0] * (n+1)
for i in range(n):
x,v = xv[i]
ans += x * bitsum(vdic[v],BIT2) - bitsum(vdic[v],BIT)
bitadd(vdic[v] , x , BIT)
bitadd(vdic[v] , 1 , BIT2)
print (ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long md = 1e9 + 7;
const int xn = 2e5 + 10;
const int xm = 5e5;
const int SQ = 750;
const int sq = 1e3 + 10;
const long long inf = 1e18 + 10;
long long power(long long a, long long b) {
return (!b ? 1
: (b & 1 ? a * power(a * a % md, b / 2) % md
: power(a * a % md, b / 2) % md));
}
int n;
map<int, int> mp;
pair<long long, long long> X[xn];
long long x[xn], v[xn], PS[xn], t[xn], ans;
void Get(int l, int r, int ind) {
for (int i = l; i <= r;) {
if (i % SQ == 0 && i + SQ - 1 <= r) {
ans -= PS[i / SQ] - x[ind] * t[i / SQ];
i += SQ;
} else {
if (v[i] <= v[ind]) ans += x[ind] - x[i];
i++;
}
}
}
void Update(int ind) {
PS[ind / SQ] += x[ind];
t[ind / SQ]++;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
cin >> n;
for (int i = 0; i < n; i++) cin >> x[i];
for (int i = 0; i < n; i++) cin >> v[i];
for (int i = 0; i < n; i++) X[i] = {x[i], v[i]};
sort(X, X + n);
for (int i = 0; i < n; i++)
x[i] = X[i].first, v[i] = X[i].second, swap(X[i].first, X[i].second),
mp[x[i]] = i;
sort(X, X + n);
for (int i = 0; i < n; i++) {
Get(0, mp[X[i].second] - 1, mp[X[i].second]);
Update(mp[X[i].second]);
}
cout << ans << '\n';
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
long long ppow(long long a, long long b, long long mod) {
a %= mod;
long long ans = 1;
while (b) {
if (b & 1) ans = ans * a % mod;
a = a * a % mod;
b >>= 1;
}
return ans;
}
long long readdd() {
long long x = 0, f = 1;
char c = getchar();
while (!isdigit(c) && c != '-') c = getchar();
if (c == '-') f = -1, c = getchar();
while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
return f * x;
}
void printtt(long long x) {
if (x < 0) putchar('-'), x = -x;
if (x >= 10) printtt(x / 10);
putchar(x % 10 + '0');
}
const long long maxm = 1e6 + 5;
long long c[maxm];
long long cc[maxm];
long long xx[maxm];
struct Node {
long long x, v;
} e[maxm];
bool cmp(Node a, Node b) {
if (a.v != b.v) {
return a.v < b.v;
} else {
return a.x < b.x;
}
}
long long lowbit(long long i) { return i & -i; }
void add(long long i, long long c[], long long t) {
while (i < maxm) {
c[i] += t;
i += lowbit(i);
}
}
long long ask(long long i, long long c[]) {
long long ans = 0;
while (i) {
ans += c[i];
i -= lowbit(i);
}
return ans;
}
signed main() {
long long n;
cin >> n;
for (long long i = 1; i <= n; i++) {
cin >> e[i].x;
xx[i] = e[i].x;
}
for (long long i = 1; i <= n; i++) {
cin >> e[i].v;
}
sort(xx + 1, xx + 1 + n);
long long num = unique(xx + 1, xx + 1 + n) - xx - 1;
for (long long i = 1; i <= n; i++) {
e[i].x = lower_bound(xx + 1, xx + 1 + num, e[i].x) - xx;
}
sort(e + 1, e + 1 + n, cmp);
long long ans = 0;
for (long long i = 1; i <= n; i++) {
if (e[i].x != 1) {
long long mi = ask(e[i].x, c);
long long temp = ask(e[i].x, cc);
temp -= mi * ((long long)1e9 - xx[e[i].x]);
ans += temp;
}
add(e[i].x, c, 1);
add(e[i].x, cc, ((long long)1e9 - xx[e[i].x]));
}
cout << ans << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class Main {
static class BIT {
int n;
long[] tree;
public BIT(int n) {
this.n = n;
tree = new long[n + 2];
}
long read(int i) {
i++;
long sum = 0;
while (i > 0) {
sum += tree[i];
i -= i & -i;
}
return sum;
}
void update(int i, int val) {
i++;
while (i <= n) {
tree[i] += val;
i += i & -i;
}
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
for(int tt=0;tt<t;tt++) {
int n= f.nextInt();
int[] x=f.readArray(n);
int[] v=f.readArray(n);
TreeSet<Integer> tree=new TreeSet<>();
for(int i:v) tree.add(i);
HashMap<Integer,Integer> map=new HashMap<>();
int curr=0;
for(int i:tree) {
curr++;
map.put(i, curr);
}
for(int i=0;i<n;i++) {
v[i]=map.get(v[i]);
}
BIT val=new BIT(200005);
BIT count=new BIT(200005);
long ans=0;
int[][] l=new int[n][2];
for(int i=0;i<n;i++) {
l[i]=new int[] {x[i],v[i]};
}
Arrays.sort(l,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return Integer.compare(a[0], b[0]);
}
});
for(int i=n-1;i>-1;i--) {
long num=count.read(n)-count.read(l[i][1]-1);
ans+=(-(long)l[i][0]*num+val.read(n)-val.read(l[i][1]-1));
count.update(l[i][1],1);
val.update(l[i][1],l[i][0]);
}
System.out.println(ans);
}
out.close();
}
static void sort(long[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (long i: p) q.add((int) i);
Collections.sort(q);
for (int i = 0; i < p.length; i++) p[i] = q.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
//Some things to notice
//Check for the overflow
//Binary Search
//Bitmask
//runtime error most of the time is due to array index out of range
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 15;
int tot = 1, N;
const int L = -2e8;
const int R = 2e8;
struct Node {
int l, r, num;
long long sum;
Node() { l = 0, r = 0, num = 0, sum = 0; }
} E[maxn * 40];
struct Point {
long long x, v;
bool operator<(const Point &T) const { return x > T.x; }
} P[maxn];
void update(int l, int r, int x, int v, int id) {
if (l == r) {
E[id].num++;
E[id].sum += x;
return;
}
int mid = (l + r) >> 1;
if (v <= mid) {
if (!E[id].l) E[id].l = ++tot;
update(l, mid, x, v, E[id].l);
} else {
if (!E[id].r) E[id].r = ++tot;
update(mid + 1, r, x, v, E[id].r);
}
E[id].num = E[E[id].l].num + E[E[id].r].num;
E[id].sum = E[E[id].l].sum + E[E[id].r].sum;
}
void getSum(int l, int r, int ln, int rn, int id, int &num, long long &sum) {
if (ln > rn) return;
if (ln == l && rn == r) {
num += E[id].num;
sum += E[id].sum;
return;
}
int mid = (l + r) >> 1;
if (ln > mid && E[id].r)
getSum(mid + 1, r, ln, rn, E[id].r, num, sum);
else if (rn <= mid && E[id].l)
getSum(l, mid, ln, rn, E[id].l, num, sum);
else {
if (E[id].r) getSum(mid + 1, r, mid + 1, rn, E[id].r, num, sum);
if (E[id].l) getSum(l, mid, ln, mid, E[id].l, num, sum);
}
}
int main() {
scanf("%d", &N);
for (int i = 1; i <= N; i++) scanf("%lld", &P[i].x);
for (int i = 1; i <= N; i++) scanf("%lld", &P[i].v);
sort(P + 1, P + 1 + N);
long long ans = 0;
for (int i = 1; i <= N; i++) {
int num = 0;
long long sum = 0;
getSum(L, R, P[i].v, R, 1, num, sum);
ans += (sum - 1LL * num * P[i].x);
update(L, R, P[i].x, P[i].v, 1);
}
printf("%lld\n", ans);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
/**
*
* @author is2ac
*/
public class D_CF {
public static void main(String[] args) throws IOException {
FastScanner58 fs = new FastScanner58();
//Reader fs = new Reader();
PrintWriter pw = new PrintWriter(System.out);
//int t = fs.ni();
int t = 1;
for (int tc = 0; tc < t; tc++) {
int n = fs.ni();
long[] x = fs.longArray(n);
long[] v = fs.longArray(n);
BIT16 bit = new BIT16(200005);
BIT16 people = new BIT16(200005);
Set<Long> set = new HashSet();
List<Long> list = new ArrayList();
Map<Long,Integer> map = new HashMap();
for (int i = 0; i < n; i++) {
set.add(v[i]);
}
for (long val : set) {
list.add(val);
}
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
map.put(list.get(i),i+1);
}
long[][] matrix = new long[n][2];
for (int i = 0; i < n; i++) {
matrix[i][0] = x[i];
matrix[i][1] = v[i];
}
Arrays.sort(matrix,new Comparator<long[]>(){
public int compare(long[] a, long[] b) {
return Long.compare(a[0],b[0]);
}
});
long res = 0;
for (int i = 0; i < n; i++) {
long cx = matrix[i][0];
int cv = map.get(matrix[i][1]);
long cur = (long)people.sum(cv) * (long)cx;
cur -= (long)bit.sum(cv);
res += cur;
people.update(cv,1);
bit.update(cv,cx);
}
pw.println(res);
}
pw.close();
}
public static long gcd(long n1, long n2) {
if (n2 == 0) {
return n1;
}
return gcd(n2, n1 % n2);
}
}
class GFG {
// A utility function to get the
// middle index of given range.
static int getMid(int s, int e)
{
return s + (e - s) / 2;
}
/*
* A recursive function to get the sum
of values in given range of the array.
* The following are parameters
for this function.
*
* st -> Pointer to segment tree
* node -> Index of current node in
* the segment tree.
* ss & se -> Starting and ending indexes
* of the segment represented
* by current node, i.e., st[node]
* l & r -> Starting and ending indexes
* of range query
*/
static long MinUtil(long[] st, int ss,
int se, int l,
int r, int node)
{
// If segment of this node is completely
// part of given range, then return
// the max of segment
if (l <= ss && r >= se)
return st[node];
// If segment of this node does not
// belong to given range
if (se < l || ss > r)
return (long)(1e11);
// If segment of this node is partially
// the part of given range
int mid = getMid(ss, se);
return Math.min(
MinUtil(st, ss, mid, l, r,
2 * node + 1),
MinUtil(st, mid + 1, se, l, r,
2 * node + 2));
}
/*
* A recursive function to update the
nodes which have the given index in their
* range. The following are parameters
st, ss and se are same as defined above
* index -> index of the element to be updated.
*/
static void updateValue(long arr[], long[]
st, int ss,
int se, int index,
long value,
int node)
{
if (index < ss || index > se) {
//System.out.println("Invalid Input");
return;
}
if (ss == se) {
// update value in array and in
// segment tree
arr[index] = value;
st[node] = value;
}
else {
int mid = getMid(ss, se);
if (index >= ss && index <= mid)
updateValue(arr, st, ss, mid,
index, value,
2 * node + 1);
else
updateValue(arr, st, mid + 1, se, index,
value, 2 * node + 2);
st[node] = Math.min(st[2 * node + 1],
st[2 * node + 2]);
}
return;
}
// Return max of elements in range from
// index l (query start) to r (query end).
static long getMin(long[] st, int n, int l, int r)
{
// Check for erroneous input values
if (l < 0 || r > n - 1 || l > r) {
//System.out.printf("Invalid Input\n");
return (long)(1e11);
}
return MinUtil(st, 0, n - 1, l, r, 0);
}
// A recursive function that constructs Segment
// Tree for array[ss..se]. si is index of
// current node in segment tree st
static long constructSTUtil(long arr[],
int ss, int se,
long[] st, int si)
{
// If there is one element in array, store
// it in current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then
// recur for left and right subtrees and
// store the max of values in this node
int mid = getMid(ss, se);
st[si] = Math.min(
constructSTUtil(arr, ss, mid,
st, si * 2 + 1),
constructSTUtil(arr, mid + 1,
se, st,
si * 2 + 2));
return st[si];
}
/*
* Function to construct segment tree from
given array. This function allocates
* memory for segment tree.
*/
static long[] constructST(long arr[], int n)
{
// Height of segment tree
int x = (int)Math.ceil(Math.log(n) / Math.log(2));
// Maximum size of segment tree
int max_size = 2 * (int)Math.pow(2, x) - 1;
// Allocate memory
long[] st = new long[max_size];
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, st, 0);
// Return the constructed segment tree
return st;
}
}
class BIT16 {
long[] bit;
public BIT16(int size) {
bit = new long[size];
}
public void update(int ind, long delta) {
while (ind < bit.length) {
bit[ind] += delta;
ind = ind + (ind & (-1 * ind));
}
}
public long sum(int ind) {
long s = 0;
while (ind > 0) {
s += bit[ind];
ind = ind - (ind & (-1 * ind));
}
return s;
}
public long query(int l, int r) {
return sum(r) - sum(l);
}
}
class UnionFind18 {
int[] id;
public UnionFind18(int size) {
id = new int[size];
for (int i = 0; i < size; i++) {
id[i] = i;
}
}
public int find(int p) {
int root = p;
while (root != id[root]) {
root = id[root];
}
while (p != root) {
int next = id[p];
id[p] = root;
p = next;
}
return root;
}
public void union(int p, int q) {
int a = find(p), b = find(q);
if (a == b) {
return;
}
id[b] = a;
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int ni() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) {
return;
}
din.close();
}
}
class FastScanner58 {
BufferedReader br;
StringTokenizer st;
public FastScanner58() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[] intArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++) {
ret[i] = ni();
}
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++) {
ret[i] = nl();
}
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author htvu
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Integer[] x = new Integer[n];
int[] v = new int[n];
long ans = 0;
Map<Integer, Integer> rank = new HashMap<>();
for (int i = 0; i < n; ++i) {
x[i] = in.nextInt();
}
for (int i = 0; i < n; ++i)
v[i] = in.nextInt();
Pair.IntPair[] ps = new Pair.IntPair[n];
for (int i = 0; i < n; ++i)
ps[i] = new Pair.IntPair(x[i], v[i]);
Arrays.sort(ps, (p1, p2) -> !p1.second.equals(p2.second) ? p1.second - p2.second : p1.first - p2.first);
Arrays.sort(x);
for (int i = 0; i < n; ++i) {
// add x[i] to pair sum
ans += (long) x[i] * (2 * i + 1 - n);
// record position of x[i] rank by v[i]
rank.put(ps[i].first, i);
}
for (int i = 0; i < n; ++i) {
// delta = how many times x[i] get overtaken (rank by x[i] - rank by v[i])
ans -= (long) x[i] * (i - rank.get(x[i]));
}
out.println(ans);
}
}
static class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> {
public A first;
public B second;
public Pair(A a, B b) {
this.first = a;
this.second = b;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) &&
second.equals(pair.second);
}
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^
(second == null ? 0 : second.hashCode());
}
public String toString() {
return "{" + first + "," + second + '}';
}
public int compareTo(Pair<A, B> o) {
int c = first.compareTo(o.first);
if (c != 0) return c;
return second.compareTo(o.second);
}
public static class IntPair extends Pair<Integer, Integer> {
public IntPair(Integer integer, Integer integer2) {
super(integer, integer2);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
class Points:
def __init__(self, x = 0, v = 0):
self.x, self.v = x, v
class Fenwick_tree:
def __init__(self, n = 0):
self.n = n
self.bit = [0] * (n + 1)
def update(self, x, value):
while x <= self.n:
self.bit[x] += value
x += x & -x
def get(self, x):
sum = 0;
while x > 0:
sum += self.bit[x];
x -= x & -x
return sum
# Input:
n, x, v = int(input()), list(map(int,input().split())), list(map(int,input().split()))
a = [Points(x[i], v[i]) for i in range(n)]
a.sort(key = lambda value: value.x)
# Compress data:
v = [a[i].v for i in range(n)]
v.sort()
data = {}
cnt = 1
for i in range(n):
if not data.__contains__(v[i]):
data[v[i]] = cnt
cnt += 1
# Solve the problem:
cnt = Fenwick_tree(n)
sum = Fenwick_tree(n)
res, i = 0, 0
for i in range(n):
a[i].v = data[a[i].v]
res += a[i].x * cnt.get(a[i].v) - sum.get(a[i].v)
cnt.update(a[i].v, 1)
sum.update(a[i].v, a[i].x)
print(res)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 10;
const int MOD = 998244353;
const int INF = 0x3f3f3f3f;
struct Node {
int x;
int v;
} a[MAXN];
bool cmp(Node a, Node b) {
if (a.v == b.v) {
return a.x < b.x;
}
return a.v < b.v;
}
int N, M;
vector<int> dic;
int main() {
int now;
long long ans;
while (~scanf("%d", &N)) {
dic.clear();
for (int i = 0; i < N; i++) {
scanf("%d", &a[i].x);
dic.push_back(a[i].x);
}
for (int i = 0; i < N; i++) {
scanf("%d", &a[i].v);
}
sort(a, a + N, cmp);
sort(dic.begin(), dic.end());
ans = 0;
for (int i = 0; i < N; i++) {
now = upper_bound(dic.begin(), dic.end(), a[i].x) - dic.begin();
ans += (long long)(now - N + i) * a[i].x;
}
printf("%lld\n", ans);
}
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
class SegmentTree():
def __init__(self,arr,func,initialRes=0):
self.f=func
self.N=len(arr)
self.tree=[0 for _ in range(4*self.N)]
self.initialRes=initialRes
for i in range(self.N):
self.tree[self.N+i]=arr[i]
for i in range(self.N-1,0,-1):
self.tree[i]=self.f(self.tree[i<<1],self.tree[i<<1|1])
def updateTreeNode(self,idx,value): #update value at arr[idx]
self.tree[idx+self.N]=value
idx+=self.N
i=idx
while i>1:
self.tree[i>>1]=self.f(self.tree[i],self.tree[i^1])
i>>=1
def query(self,l,r): #get sum (or whatever function) on interval [l,r] inclusive
r+=1
res=self.initialRes
l+=self.N
r+=self.N
while l<r:
if l&1:
res=self.f(res,self.tree[l])
l+=1
if r&1:
r-=1
res=self.f(res,self.tree[r])
l>>=1
r>>=1
return res
def getMaxSegTree(arr):
return SegmentTree(arr,lambda a,b:max(a,b),initialRes=-float('inf'))
def getMinSegTree(arr):
return SegmentTree(arr,lambda a,b:min(a,b),initialRes=float('inf'))
def getSumSegTree(arr):
return SegmentTree(arr,lambda a,b:a+b,initialRes=0)
def main():
n=int(input())
xes=readIntArr()
ves=readIntArr()
#perform coordinate compression on xes. Compressed values shall be the indexes of segment tree
xes2=list(sorted(xes)) #xes2[compressed]=x
xTox2Map=dict()
for i,x in enumerate(xes2):
xTox2Map[x]=i #xTox2Map[x]=i
arr=[] #[original x, compressed x, v]
for i in range(n):
arr.append([xes[i],xTox2Map[xes[i]],ves[i]])
arr.sort(key=lambda x:(x[2],x[0])) #sort by v asc, then position asc
segArray=[0 for _ in range(n)] #index shall be compressed x, value is actual x
st=getSumSegTree(segArray) #for sum of xes
stCnts=getSumSegTree(segArray.copy()) #for counts
# print(arr)
ans=0
for originalX,compressedX,v in arr:
smallerSums=st.query(0,compressedX)
smallerCounts=stCnts.query(0,compressedX)
ans+=originalX*smallerCounts-smallerSums
st.updateTreeNode(compressedX,originalX) #update the tree
stCnts.updateTreeNode(compressedX,1)
# print(ans)
print(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# import sys
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
inf=float('inf')
MOD=10**9+7
main()
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.util.Arrays;
import java.util.Scanner;
import java.util.Comparator;
public class MovingPoints {
private static long sumaj(long[] arr,int index) {
long result=0;
while (index>=0) {
result+=arr[index];
index=(index&(index+1))-1;
}
return result;
}
private static void apdejt (long[] t,int index,int vv) {
while (index<t.length) {
t[index]+=vv;
index=index|(index + 1);
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[][] pm=new int[n][2];
int[][] vm=new int[n][2];
for (int i=0;i<n;i++)
pm[i][0]=in.nextInt();
for (int i=0;i<n;i++) {
pm[i][1]=in.nextInt();
vm[i][0]=pm[i][1];
vm[i][1]=i;
}
in.close();
Arrays.sort(vm, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
int nss=0;
int[][] finar=new int[n][2];
for (int i=0;i<n;i++) {
if (i>0 && vm[i][0]!=vm[i-1][0])
nss++;
finar[i][0]=nss;
finar[i][1]=vm[i][1];
}
Arrays.sort(finar,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[1]-b[1];
}});
for (int i=0; i<n;i++) {
pm[i][1] = finar[i][0];
}
Arrays.sort(pm,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[0]-b[0];
}});
long[] c=new long[n];
long[] pts=new long[n];
long totalsum=0;
for (int i=0;i<n;i++) {
int index=pm[i][1];
totalsum+=sumaj(pts,index)*pm[i][0]-sumaj(c,index);
apdejt(pts,index,1);
apdejt(c, index, pm[i][0]);
}
System.out.println(totalsum);
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
void coordinatecompress(vector<int> &data) {
int n = data.size();
vector<pair<int, int> > tempdata(n);
for (int i = 0; i < n; i++) tempdata[i] = {data[i], i};
sort(tempdata.begin(), tempdata.end());
data[tempdata[0].second] = 0;
for (int i = 1; i < n; i++)
data[tempdata[i].second] = data[tempdata[i - 1].second] +
(tempdata[i - 1].first != tempdata[i].first);
}
struct segTree {
long long cnt, sum;
};
const int N = 2e5;
segTree tree[4 * N + 1], lazy[4 * N + 1];
void updt(int s, int e, int node, int l, int r, int val) {
tree[node].sum += lazy[node].sum * (e - s + 1);
tree[node].cnt += lazy[node].cnt * (e - s + 1);
int mid = (s + e) / 2;
if (s != e) {
lazy[2 * node + 1].sum += lazy[node].sum;
lazy[2 * node + 2].sum += lazy[node].sum;
lazy[2 * node + 1].cnt += lazy[node].cnt;
lazy[2 * node + 2].cnt += lazy[node].cnt;
}
lazy[node] = {0, 0};
if (r < s || l > e) return;
if (s >= l && e <= r) {
tree[node].sum += val * (e - s + 1);
tree[node].cnt += e - s + 1;
if (s != e) {
lazy[2 * node + 1].sum += val;
lazy[2 * node + 2].sum += val;
lazy[2 * node + 1].cnt++;
;
lazy[2 * node + 2].cnt++;
;
}
return;
}
updt(s, mid, 2 * node + 1, l, r, val);
updt(mid + 1, e, 2 * node + 2, l, r, val);
tree[node].sum = tree[2 * node + 1].sum + tree[2 * node + 2].sum;
tree[node].cnt = tree[2 * node + 1].cnt + tree[2 * node + 2].cnt;
}
segTree qry(int s, int e, int node, int i, int j) {
tree[node].sum += lazy[node].sum * (e - s + 1);
tree[node].cnt += lazy[node].cnt * (e - s + 1);
int mid = (s + e) / 2;
if (s != e) {
lazy[2 * node + 1].sum += lazy[node].sum;
lazy[2 * node + 2].sum += lazy[node].sum;
lazy[2 * node + 1].cnt += lazy[node].cnt;
lazy[2 * node + 2].cnt += lazy[node].cnt;
}
lazy[node] = {0, 0};
if (e < i || s > j) return {0, 0};
if (s >= i && e <= j) {
return tree[node];
}
segTree ans1 = qry(s, mid, 2 * node + 1, i, j),
ans2 = qry(mid + 1, e, 2 * node + 2, i, j);
tree[node].sum = ans1.sum + ans2.sum;
tree[node].cnt = ans1.cnt + ans2.cnt;
return tree[node];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
vector<pair<int, int> > point(n);
vector<int> p(n), v(n), tmp, org(n);
for (int i = 0; i < n; i++) cin >> p[i];
for (int i = 0; i < n; i++) cin >> v[i];
tmp = p;
coordinatecompress(p);
for (int i = 0; i < n; i++) {
org[p[i]] = tmp[i];
point[i] = {v[i], p[i]};
}
long long ans = 0;
sort(point.begin(), point.end());
for (auto [s, x] : point) {
segTree res = qry(0, n - 1, 0, x, x);
ans += res.cnt * org[x] - res.sum;
updt(0, n - 1, 0, x + 1, n - 1, org[x]);
}
cout << ans;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
# -*- coding: utf-8 -*-
import sys
from collections import Counter
from bisect import bisect_left
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
# sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7
class BIT:
def __init__(self, n):
n += 1
nv = 1
while nv < n:
nv *= 2
self.size = nv
self.tree = [0] * nv
def sum(self, i):
s = 0
i += 1
while i > 0:
s += self.tree[i-1]
i -= i & -i
return s
def add(self, i, x):
i += 1
while i <= self.size:
self.tree[i-1] += x
i += i & -i
def get(self, l, r=None):
if r is None: r = l + 1
res = 0
if r: res += self.sum(r-1)
if l: res -= self.sum(l-1)
return res
def update(self, i, x):
self.add(i, x - self.get(i))
N = INT()
A = LIST()
B = LIST()
AB = list(zip(A, B))
AB.sort()
B = sorted(set(B))
M = len(B)
bit1 = BIT(M)
bit2 = BIT(M)
ans = 0
for a, b in AB:
pos = bisect_left(B, b)
sm = bit1.sum(pos)
cnt = bit2.sum(pos)
ans += cnt * a - sm
bit1.add(pos, a)
bit2.add(pos, 1)
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class Main {
static class Pair implements Comparable<Pair> {
int x, v;
Pair(int x, int v) {
this.x = x;
this.v = v;
}
public int compareTo(Pair p) {
return x - p.x;
}
}
static class SegmentTree {
int n;
long[] t;
SegmentTree(int n) {
this.n = n;
int h = (int)(Math.ceil(Math.log(n) / Math.log(2)));
t = new long[1 << (h + 1)];
}
void update(int idx, long diff) {
update(1, 0, n - 1, idx, diff);
}
void update(int n, int s, int e, int idx, long diff) {
if (idx < s || e < idx) {
return;
}
t[n] += diff;
if (s != e) {
update(2 * n, s, (s + e) / 2, idx, diff);
update(2 * n + 1, (s + e) / 2 + 1, e, idx, diff);
}
}
long sum(int l, int r) {
return sum(1, 0, n - 1, l, r);
}
long sum(int n, int s, int e, int l, int r) {
if (r < s || e < l) {
return 0;
} else if (l <= s && e <= r) {
return t[n];
} else {
return sum(2 * n, s, (s + e) / 2, l, r) + sum(2 * n + 1, (s + e) / 2 + 1, e, l, r);
}
}
}
public static void main(String[] args) {
InputReader in = new InputReader();
int N = in.nextInt();
int[] x = new int[N];
int[] v = new int[N];
Pair[] p = new Pair[N];
for (int i = 0; i < N; i++) {
x[i] = in.nextInt();
}
for (int i = 0; i < N; i++) {
v[i] = in.nextInt();
}
for (int i = 0; i < N; i++) {
p[i] = new Pair(x[i], v[i]);
}
Arrays.sort(p, new Comparator<Pair>() {
public int compare(Pair p1, Pair p2) {
return Integer.compare(p1.v, p2.v);
}
});
Map<Integer, Integer> map = new HashMap<>();
int idx = 0;
for (int i = 0; i < N; i++) {
if (map.containsKey(p[i].v)) {
continue;
}
map.put(p[i].v, idx++);
}
Arrays.sort(p);
SegmentTree seg1 = new SegmentTree(N);
SegmentTree seg2 = new SegmentTree(N);
long ans = 0;
for (int i = 0; i < N; i++) {
ans += seg2.sum(0, map.get(p[i].v)) * p[i].x;
ans -= seg1.sum(0, map.get(p[i].v));
seg1.update(map.get(p[i].v), p[i].x);
seg2.update(map.get(p[i].v), 1);
}
System.out.println(ans);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer st;
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long>> v;
long long arr[200005];
map<long long, long long> mp;
map<long long, long long> rmp;
pair<long long, long long> bit[200005];
set<long long> s;
void insert(long long ind) {
for (long long i = ind; i < 200005; i += i & -i)
bit[i].first += 1, bit[i].second += rmp[ind];
}
pair<long long, long long> query(long long ind) {
pair<long long, long long> ret = {0, 0};
if (ind == 0) return ret;
for (long long i = ind; i > 0; i -= i & -i)
ret.first += bit[i].first, ret.second += bit[i].second;
return ret;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long n;
cin >> n;
for (long long i = 0; i < n; i++) cin >> arr[i], s.insert(arr[i]);
long long c = 1;
for (auto i : s) rmp[c] = i, mp[i] = c++;
for (long long i = 0; i < n; i++) {
long long ve;
cin >> ve;
v.push_back({ve, mp[arr[i]]});
}
sort(v.begin(), v.end(), greater<pair<long long, long long>>());
long long ans = 0;
c = 0;
long long val = 0;
for (auto i : v) {
pair<long long, long long> q = query(i.second);
long long num = c - q.first;
long long sum = val - q.second;
ans += (sum - num * rmp[i.second]);
c++;
val += rmp[i.second];
insert(i.second);
}
cout << ans << "\n";
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
// package Quarantine;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class MovingPoints {
public static void update(int tree[],int val,int ind,int size){
while(ind<=size){
tree[ind]+=val;
ind+=(ind&(-ind));
}
return;
}
public static void update(long tree[],int val,int ind,int size){
while(ind<=size){
tree[ind]+=val;
ind+=(ind&(-ind));
}
return;
}
public static long query(long tree[],int ind){
long sum=0;
while(ind>0){
sum+=tree[ind];
ind-=(ind&(-ind));
}
return sum;
}
public static long query(int tree[],int ind){
long sum=0;
while(ind>0){
sum+=tree[ind];
ind-=(ind&(-ind));
}
return sum;
}
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
StringTokenizer st=new StringTokenizer(br.readLine());
int x[]=new int[n+1];
for(int i=1;i<=n;i++){
x[i]=Integer.parseInt(st.nextToken());
}
st=new StringTokenizer(br.readLine());
int v[]=new int[n+1];
for(int i=1;i<=n;i++){
v[i]=Integer.parseInt(st.nextToken());
}
ArrayList<Particle> particles=new ArrayList<>();
TreeSet<Integer> set=new TreeSet<>();
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=1;i<=n;i++){
particles.add(new Particle(x[i],v[i]));
set.add(v[i]);
}
Collections.sort(particles);
int count=1;
for(int k:set){
map.put(k,count++);
}
int numtree[]=new int[count];
long coordi[]=new long[count];
count--;
// System.out.println(map.toString());
long ans=0;
for(int i=n-1;i>=0;i--){
Particle curr=particles.get(i);
int vt=map.get(curr.v);
long num=query(numtree,count)-query(numtree,vt-1);
long sum=query(coordi,count)-query(coordi,vt-1);
// System.out.println(curr.x+" "+num+" "+sum);
long temp=sum-num*curr.x;
ans+=temp;
update(numtree,1,vt,count);
update(coordi,curr.x,vt,count);
}
System.out.println(ans);
}
}
class Particle implements Comparable<Particle>{
int x,v;
public Particle(int x,int v){
this.x=x;
this.v=v;
}
@Override
public int compareTo(Particle o) {
return this.x-o.x;
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const ll INF = static_cast<ll>(1e18);
struct FlowEdge {
int v, u;
long long cap, flow = 0;
FlowEdge(int v, int u, long long cap) : v(v), u(u), cap(cap) {}
};
struct Dinic {
const long long flow_inf = 1e18;
vector<FlowEdge> edges;
vector<vector<int>> adj;
int n, m = 0;
int s, t;
vector<int> level, ptr;
queue<int> q;
Dinic(int n, int s, int t) : n(n), s(s), t(t) {
adj.resize(n);
level.resize(n);
ptr.resize(n);
}
void add_edge(int v, int u, long long cap) {
edges.emplace_back(v, u, cap);
edges.emplace_back(u, v, 0);
adj[v].push_back(m);
adj[u].push_back(m + 1);
m += 2;
}
bool bfs() {
while (!q.empty()) {
int v = q.front();
q.pop();
for (int id : adj[v]) {
if (edges[id].cap - edges[id].flow < 1) continue;
if (level[edges[id].u] != -1) continue;
level[edges[id].u] = level[v] + 1;
q.push(edges[id].u);
}
}
return level[t] != -1;
}
long long dfs(int v, long long pushed) {
if (pushed == 0) return 0;
if (v == t) return pushed;
for (int& cid = ptr[v]; cid < (int)adj[v].size(); cid++) {
int id = adj[v][cid];
int u = edges[id].u;
if (level[v] + 1 != level[u] || edges[id].cap - edges[id].flow < 1)
continue;
long long tr = dfs(u, min(pushed, edges[id].cap - edges[id].flow));
if (tr == 0) continue;
edges[id].flow += tr;
edges[id ^ 1].flow -= tr;
return tr;
}
return 0;
}
long long flow() {
long long f = 0;
while (true) {
fill(level.begin(), level.end(), -1);
level[s] = 0;
q.push(s);
if (!bfs()) break;
fill(ptr.begin(), ptr.end(), 0);
while (long long pushed = dfs(s, flow_inf)) {
f += pushed;
}
}
return f;
}
};
template <typename T>
struct FenwickTree {
vector<T> bit;
FenwickTree(int sz) : bit(sz + 1) {}
void update(int x, T delta) {
for (int i = ++x; i < bit.size(); i += i & -i) bit[i] += delta;
}
T query(int x) {
T ans{};
for (int i = ++x; i > 0; i -= i & -i) ans += bit[i];
return ans;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
srand(time(nullptr));
int n;
cin >> n;
vector<pair<int, int>> P(n);
for (int i = 0; i < n; i++) cin >> P[i].first;
set<int> speeds, pos;
for (int i = 0; i < n; i++) {
cin >> P[i].second;
speeds.insert(P[i].second);
pos.insert(P[i].first);
}
int cnt = 0;
map<int, int> mp;
for (int s : speeds) mp[s] = cnt++;
sort(P.begin(), P.end());
ll tot = 0, pt = 0;
for (int i = 0; i < n; i++) {
tot += 1LL * i * P[i].first - pt;
pt += P[i].first;
}
const int MAXS = cnt + 10;
FenwickTree<ll> fenw(MAXS);
FenwickTree<int> fpos(MAXS);
for (int i = 0; i < n; i++) {
ll times = fpos.query(MAXS - 1) - fpos.query(mp[P[i].second]);
tot -= (1LL * P[i].first * times);
tot += fenw.query(MAXS - 1) - fenw.query(mp[P[i].second]);
fenw.update(mp[P[i].second], P[i].first);
fpos.update(mp[P[i].second], +1);
}
cout << tot << '\n';
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
import sys
input=sys.stdin.readline
def getsum(BITTree,i):
s = 0
while i > 0:
s += BITTree[i]
i -= i & (-i)
return(s)
def updatebit(BITTree , n , i ,v):
while i <= n:
BITTree[i] += v
i += i & (-i)
n=int(input())
x=[int(i) for i in input().split() if i!='\n']
v=[int(i) for i in input().split() if i!='\n']
for i in range(n):
v[i]=[v[i],i]
v.sort()
pos=dict()
store,prev=1,v[0][0]
for i in range(n):
if i>0:
if prev==v[i][0]:
pos[x[v[i][1]]]=store
else:
store+=1
pos[x[v[i][1]]]=store
prev=v[i][0]
else:
pos[x[v[i][1]]]=store
sort=sorted(pos.keys())
bit=[0]*(n+1)
ind=[0]*(n+1)
ans,count,diff=0,0,0
length=max(sort)
total=0
for i in range(len(sort)-1,-1,-1):
count=getsum(bit,pos[sort[i]]-1)
diff=getsum(ind,pos[sort[i]]-1)
if i<(n-1):
total+=(sort[i+1]-sort[i])*(n-1-i)
ans+=total-(diff-count*sort[i])
updatebit(bit,len(bit)-1,pos[sort[i]],1)
updatebit(ind,len(ind)-1,pos[sort[i]],sort[i])
print(int(ans))
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long mx = 2 * 1e5 + 5;
const long long mod = 1e9 + 7;
long long sum[mx];
long long num[mx];
void update(int pos, int value) {
while (pos <= mx) {
sum[pos] += value;
num[pos]++;
pos += (pos & -pos);
}
}
pair<int, long long> query(int pos) {
long long summ = 0;
long long numm = 0;
while (pos >= 1) {
summ += sum[pos];
numm += num[pos];
pos -= (pos & -pos);
}
return {numm, summ};
}
int main() {
int n;
cin >> n;
pair<long long, long long> p[n];
map<long long, int> mp;
for (int i = 0; i < n; i++) {
cin >> p[i].first;
}
for (int i = 0; i < n; i++) {
cin >> p[i].second;
mp[p[i].second] = i;
}
int cur = 1LL;
for (auto& i : mp) {
i.second = cur;
cur++;
}
for (int i = 0; i < n; i++) {
p[i].second = mp[p[i].second];
}
sort(p, p + n);
long long ans = 0;
for (int i = 0; i < n; i++) {
long long myv = p[i].second;
long long myx = p[i].first;
pair<long long, long long> cnt = query(myv);
ans += (1LL * myx * cnt.first);
ans -= cnt.second;
update(myv, myx);
}
cout << ans;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 10;
struct node {
long long a;
long long t;
} w[N];
bool cmp(node a, node b) { return a.a < b.a; }
long long c[N][2], cnt[N], n;
long long lowbit(long long x) { return x & (-x); }
void add(long long x, long long val) {
while (x <= n) c[x][0]++, c[x][1] += val, x += lowbit(x);
}
long long ask(long long x, long long k) {
long long res = 0;
while (x) res += c[x][k], x -= lowbit(x);
return res;
}
long long ans = 0, len = 0;
struct EDGE {
long long to, next;
long long dis;
} edge[N];
struct ha {
long long pos;
long long dis;
friend bool operator<(ha a, ha b) { return a.dis > b.dis; }
};
long long tot;
long long head[N];
long long dis[N];
bool vis[N];
void Init(long long n) {
for (long long i = 1; i <= n; ++i) dis[i] = 1;
}
void add(long long from, long long to, long long cost) {
++tot;
edge[tot].to = to;
edge[tot].dis = cost;
edge[tot].next = head[from];
head[from] = tot;
}
priority_queue<ha> q;
void Dijkstra(long long s) {
dis[s] = 0;
q.push({s, 0});
while (!q.empty()) {
ha tmp = q.top();
q.pop();
long long x = tmp.pos;
if (vis[x]) continue;
vis[x] = 1;
for (long long i = head[x]; i; i = edge[i].next) {
long long y = edge[i].to;
if (dis[y] > dis[x] + edge[i].dis) {
dis[y] = dis[x] + edge[i].dis;
if (!vis[y]) {
q.push({y, dis[y]});
}
}
}
}
}
void solve() {
ios::sync_with_stdio(false), cin.tie(0);
cin >> n;
for (long long i = 1; i <= n; i++) cin >> w[i].a;
for (long long i = 1; i <= n; i++) cin >> w[i].t, cnt[++len] = w[i].t;
sort(w + 1, w + 1 + n, cmp);
sort(cnt + 1, cnt + 1 + len);
len = unique(cnt + 1, cnt + 1 + len) - cnt - 1;
for (long long i = 1; i <= n; i++) {
long long now = lower_bound(cnt + 1, cnt + 1 + len, w[i].t) - cnt;
ans += w[i].a * ask(now, 0) - ask(now, 1);
add(now, w[i].a);
}
cout << ans << '\n';
}
signed main() {
solve();
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
class STlazy {
private:
int n;
vector<long long> node, lazy;
public:
STlazy(vector<long long> v) {
int siz = v.size();
n = 1;
while (n < siz) n *= 2;
node.resize(2 * n - 1, 0);
lazy.resize(2 * n - 1, 0);
for (int i = 0; i < siz; i++) node[n - 1 + i] = v[i];
for (int i = n - 2; i >= 0; i--)
node[i] = node[2 * i + 1] + node[2 * i + 2];
}
void eval(int k, int l, int r) {
if (lazy[k] == 0) return;
node[k] += lazy[k];
if (r - l > 1) {
lazy[2 * k + 1] += lazy[k] / 2;
lazy[2 * k + 2] += lazy[k] / 2;
}
lazy[k] = 0;
}
void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {
if (r < 0) r = n;
eval(k, l, r);
if (r <= a || b <= l) return;
if (a <= l && r <= b) {
lazy[k] += (r - l) * x;
eval(k, l, r);
return;
}
add(a, b, x, 2 * k + 1, l, (l + r) / 2);
add(a, b, x, 2 * k + 2, (l + r) / 2, r);
node[k] = node[2 * k + 1] + node[2 * k + 2];
}
long long query(int a, int b, int k = 0, int l = 0, int r = -1) {
if (r < 0) r = n;
if (r <= a || b <= l) return 0;
eval(k, l, r);
if (a <= l && r <= b) return node[k];
long long lx = query(a, b, 2 * k + 1, l, (l + r) / 2);
long long rx = query(a, b, 2 * k + 2, (l + r) / 2, r);
return lx + rx;
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<pair<int, int> > vp(n);
for (int i = 0; i < n; i++) {
cin >> vp[i].first;
}
for (int i = 0; i < n; i++) {
cin >> vp[i].second;
}
sort(vp.begin(), vp.end());
vector<long long> vel;
for (pair<int, int> &p : vp) vel.push_back(p.second);
sort(vel.begin(), vel.end());
vel.erase(unique(vel.begin(), vel.end()), vel.end());
auto f = [&](long long x) -> int {
return lower_bound(vel.begin(), vel.end(), x) - vel.begin();
};
int siz = vel.size();
vector<long long> tmp(siz, 0), cnt(siz, 0);
for (pair<int, int> &p : vp) {
int pos = f(p.second);
tmp[pos] += p.first;
cnt[pos]++;
}
STlazy A(tmp), B(cnt);
long long ans = 0;
for (int i = 0; i < n; i++) {
int v = vp[i].second;
int pos = f(v);
A.add(pos, pos + 1, -vp[i].first);
B.add(pos, pos + 1, -1);
if (v == 0) {
ans += A.query(pos, siz + 1) - B.query(pos, siz + 1) * vp[i].first;
} else if (v > 0) {
ans += A.query(pos, siz + 1) - B.query(pos, siz + 1) * vp[i].first;
} else if (v < 0) {
ans += A.query(pos, siz + 1) - B.query(pos, siz + 1) * vp[i].first;
}
}
cout << ans << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 200005;
map<long long, long long> g;
map<long long, long long> invG;
long long tree[8][maxn];
long long sum(long long k, long long t) {
long long res = 0;
for (long long i = k; i >= 1; i -= i & -i) res += tree[t][i];
return res;
}
void add(long long k, long long v, long long t) {
for (long long i = k; i < maxn; i += i & -i) tree[t][i] += v;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
for (long long i = 0; i < maxn; i++)
for (long long j = 0; j < 8; j++) tree[j][i] = 0;
long long n;
cin >> n;
priority_queue<pair<long long, pair<long long, long long>>> pq;
vector<long long> xs;
vector<long long> vs;
set<long long> distinct;
for (long long i = 0; i < n; i++) {
long long x;
cin >> x;
xs.push_back(x);
distinct.emplace(x);
}
for (long long i = 0; i < n; i++) {
long long v;
cin >> v;
vs.push_back(v);
}
vector<long long> vec(distinct.begin(), distinct.end());
for (long long i = 0; i < n; i++) {
g[vec[i]] = i + 1;
invG[i + 1] = vec[i];
}
for (long long i = 0; i < n; i++) {
long long dir = 0;
if (vs[i] < 0) dir = 1;
pq.emplace(abs(vs[i]), make_pair(g[xs[i]], dir));
}
long long res = 0;
while (!pq.empty()) {
pair<long long, pair<long long, long long>> t = pq.top();
queue<pair<long long, long long>> q;
queue<pair<long long, long long>> q2;
while (!pq.empty() && pq.top().first == t.first) {
pair<long long, pair<long long, long long>> p = pq.top();
pq.pop();
q.emplace(p.second);
}
while (!q.empty()) {
pair<long long, long long> p = q.front();
q.pop();
q2.emplace(p);
long long x = p.first;
long long dir = p.second;
long long sumRight = sum(maxn - 1, 0) - sum(x, 0);
sumRight -= invG[x] * (sum(maxn - 1, 0 + 2) - sum(x, 0 + 2));
long long sumLeft = sum(x - 1, 1);
sumLeft -= invG[x] * sum(x - 1, 1 + 2);
res += abs(sumRight) + abs(sumLeft);
}
vector<pair<long long, long long>> same;
while (!q2.empty()) {
pair<long long, long long> p = q2.front();
q2.pop();
long long x = p.first;
long long dir = p.second;
add(x, invG[x], dir);
add(x, 1, dir + 2);
same.push_back(make_pair(x, dir));
add(x, invG[x], dir + 4);
add(x, 1, dir + 4 + 2);
}
long long cnt = 0;
for (pair<long long, long long> p : same) {
long long x = p.first;
long long dir = p.second;
if (dir == 0) {
long long sumRight = sum(maxn - 1, 4) - sum(x, 4);
sumRight -= invG[x] * (sum(maxn - 1, 4 + 2) - sum(x, 4 + 2));
long long sumLeft = sum(x - 1, 5);
sumLeft -= invG[x] * sum(x - 1, 5 + 2);
long long extra = sum(x - 1, 4);
extra -= invG[x] * sum(x - 1, 4 + 2);
cnt += abs(sumRight) + abs(sumLeft) + abs(extra);
} else {
long long sumRight = sum(maxn - 1, 4) - sum(x, 4);
sumRight -= invG[x] * (sum(maxn - 1, 4 + 2) - sum(x, 4 + 2));
long long sumLeft = sum(x - 1, 5);
sumLeft -= invG[x] * sum(x - 1, 5 + 2);
long long extra = sum(maxn - 1, 5) - sum(x, 5);
extra -= invG[x] * (sum(maxn - 1, 5 + 2) - sum(x, 5 + 2));
cnt += abs(sumRight) + abs(sumLeft) + abs(extra);
}
}
cnt /= 2;
res += cnt;
for (pair<long long, long long> p : same) {
long long x = p.first;
long long dir = p.second;
add(x, -invG[x], dir + 4);
add(x, -1, dir + 4 + 2);
}
}
cout << res << '\n';
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 22, inf = 1e9 + 7;
int n;
long long s[4 * N], cursum;
vector<pair<int, int> > t[4 * N];
vector<long long> p[4 * N];
pair<int, int> a[N];
void build(int v, int tl, int tr) {
if (tl == tr) {
s[v] = a[tl].first;
t[v].push_back({a[tl].second, a[tl].first});
p[v].push_back(a[tl].first);
return;
}
int tm = (tl + tr) / 2;
build(v * 2, tl, tm);
build(v * 2 + 1, tm + 1, tr);
s[v] = s[v * 2] + s[v * 2 + 1];
t[v].resize(tr - tl + 1);
p[v].resize(tr - tl + 1);
merge(t[v * 2].begin(), t[v * 2].end(), t[v * 2 + 1].begin(),
t[v * 2 + 1].end(), t[v].begin());
for (int i = 0; i < t[v].size(); i++) {
if (i == 0)
p[v][i] = t[v][i].second;
else
p[v][i] = p[v][i - 1] + t[v][i].second;
}
}
long long sum(int v, int tl, int tr, int l, int r) {
if (l <= tl && tr <= r) {
return s[v];
}
if (tl > r || tr < l) return 0LL;
int tm = (tl + tr) / 2;
return sum(v * 2, tl, tm, l, r) + sum(v * 2 + 1, tm + 1, tr, l, r);
}
int get(int v, int tl, int tr, int l, int r, int val) {
if (l <= tl && tr <= r) {
int id = lower_bound(t[v].begin(), t[v].end(), make_pair(val, -inf)) -
t[v].begin();
if (id != 0) cursum += p[v][id - 1];
return id;
}
if (tl > r || tr < l) {
return 0;
}
int tm = (tl + tr) / 2;
return get(v * 2, tl, tm, l, r, val) + get(v * 2 + 1, tm + 1, tr, l, r, val);
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i].first;
}
for (int i = 1; i <= n; i++) {
cin >> a[i].second;
}
sort(a + 1, a + n + 1);
build(1, 1, n);
long long ans = 0;
for (int i = 1; i <= n; i++) {
cursum = 0;
int cnt = get(1, 1, n, i + 1, n, a[i].second);
long long cur = 0;
cur += sum(1, 1, n, i + 1, n);
cur -= cursum;
cur -= a[i].first * 1LL * (n - i - cnt);
ans += cur;
}
cout << endl;
cout << ans;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
//package codeforces.round624div3;
import java.io.*;
import java.util.*;
public class MovingPoints {
private static int UNVISITED = 0;
private static int VISITING = -1;
private static int VISITED = 1;
public static void main(String[] args) {
// try {
// FastScanner in = new FastScanner(new FileInputStream("src/input.in"));
// PrintWriter out = new PrintWriter(new FileOutputStream("src/output.out"));
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
solve(1, in, out);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
private static void solve(int q, FastScanner in, PrintWriter out) {
for (int qq = 0; qq < q; qq++) {
int n = in.nextInt();
int[] x = new int[n];
for(int i = 0; i < n; i++) {
x[i] = in.nextInt();
}
Integer[] v = new Integer[n];
for(int i = 0;i < n; i++) {
v[i] = in.nextInt();
}
v = ArrayUtils.compress(v);
BinaryIndexedTree cntBit = new BinaryIndexedTree(n);
BinaryIndexedTree sumBit = new BinaryIndexedTree(n);
int[][] p = new int[n][2];
for(int i = 0; i < n; i++) {
p[i][0] = x[i];
p[i][1] = v[i];
}
Arrays.sort(p, Comparator.comparingInt(a -> a[0]));
long sum = 0;
for(int i = 0; i < n; i++) {
long prevCnt = cntBit.rangeSum(p[i][1]);
long prevSum = sumBit.rangeSum(p[i][1]);
sum += (prevCnt * p[i][0] - prevSum);
cntBit.adjust(p[i][1], 1);
sumBit.adjust(p[i][1], p[i][0]);
}
out.println(sum);
}
out.close();
}
private static class ArrayUtils {
/*
Compress all values of a to its rank in [1, a.length]
*/
private static Integer[] compress(Integer[] a) {
int n = a.length;
Integer[] ret = new Integer[n];
Integer[] copy = Arrays.copyOf(a, n);
Arrays.sort(copy);
int rank = 1;
Map<Integer, Integer> map = new HashMap<>();
for(int v : copy) {
if(!map.containsKey(v)) {
map.put(v, rank);
rank++;
}
}
for(int i = 0; i < n; i++) {
ret[i] = map.get(a[i]);
}
return ret;
}
}
private static class BinaryIndexedTree {
private long[] ft;
private BinaryIndexedTree(int n) {
ft = new long[n + 1];
}
private long rangeSum(int l, int r) {
return rangeSum(r) - (l == 1 ? 0 : rangeSum(l - 1));
}
private long rangeSum(int r) {
long sum = 0;
for(; r > 0; r -= leastSignificantOne(r)) {
sum += ft[r];
}
return sum;
}
private void adjust(int k, int diff) {
for(; k < ft.length; k += leastSignificantOne(k)) {
ft[k] += diff;
}
}
private int leastSignificantOne(int i) {
return i & (-i);
}
}
private static long modularAdd(long a, long b, int mod) {
long sum = a + b;
if (sum >= mod) {
sum -= mod;
}
return sum;
}
private static long modularSubtract(long a, long b, int mod) {
long diff = a - b;
if (diff < 0) {
diff += mod;
}
return diff;
}
private static Stack<Integer> topologicalSort(Set<Integer>[] g) {
Stack<Integer> stack = new Stack<>();
int[] state = new int[g.length];
for (int node = 0; node < g.length; node++) {
if (!topoSortHelper(g, stack, state, node)) {
return null;
}
}
return stack;
}
private static boolean topoSortHelper(Set<Integer>[] g, Stack<Integer> stack, int[] state, int currNode) {
if (state[currNode] == VISITED) {
return true;
} else if (state[currNode] == VISITING) {
return false;
}
state[currNode] = VISITING;
for (int neighbor : g[currNode]) {
if (!topoSortHelper(g, stack, state, neighbor)) {
return false;
}
}
state[currNode] = VISITED;
stack.push(currNode);
return true;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
long long c1[maxn], c2[maxn];
void add(long long *c, int x, int y) {
for (; x < maxn; x += x & -x) c[x] += y;
}
long long ask(long long *c, int x) {
long long ret = 0;
for (; x > 0; x -= x & -x) ret += c[x];
return ret;
}
struct node {
int x, v;
} p[maxn];
int b[maxn];
bool cmp(node a, node b) {
if (a.x == b.x) return a.v < b.v;
return a.x < b.x;
}
int main() {
int n;
cin >> n;
int m = 0;
for (int i = 0; i < n; i++) scanf("%d", &p[i].x);
for (int i = 0; i < n; i++) {
scanf("%d", &p[i].v);
b[m++] = p[i].v;
}
sort(b, b + m);
m = unique(b, b + m) - b;
for (int i = 0; i < n; i++) {
p[i].v = lower_bound(b, b + m, p[i].v) - b + 1;
}
sort(p, p + n, cmp);
long long Ans = 0;
for (int i = 0; i < n; i++) {
long long cnt = ask(c1, p[i].v), sum = ask(c2, p[i].v);
Ans += cnt * p[i].x - sum;
add(c1, p[i].v, 1);
add(c2, p[i].v, p[i].x);
}
cout << Ans << endl;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n, i;
pair<int, int> dot[N];
long long mergeMoving(pair<int, int> arr[], pair<int, int> temp[], int left,
int right);
long long merge(pair<int, int> arr[], pair<int, int> temp[], int left, int mid,
int right);
long long movingdot(pair<int, int> arr[], int array_size) {
pair<int, int> temp[array_size];
return mergeMoving(arr, temp, 0, array_size - 1);
}
long long mergeMoving(pair<int, int> arr[], pair<int, int> temp[], int left,
int right) {
int mid;
long long dis = 0LL;
mid = right + left >> 1;
if (left != mid) dis += mergeMoving(arr, temp, left, mid);
if (right != mid + 1) dis += mergeMoving(arr, temp, mid + 1, right);
dis += merge(arr, temp, left, mid + 1, right);
return dis;
}
long long merge(pair<int, int> arr[], pair<int, int> temp[], int left, int mid,
int right) {
int i = left;
int j = mid;
int k = left;
long long dis = 0;
long long quick[right + 1];
for (i = left; i <= right; i++) {
dis += arr[i].first;
quick[i] = dis;
}
dis = 0;
i = left;
while ((i < mid) && (j < right + 1)) {
if (arr[i].second <= arr[j].second) {
dis = dis + quick[right] - quick[j - 1] -
1LL * (right - j + 1) * arr[i].first;
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid - 1) temp[k++] = arr[i++];
while (j <= right) temp[k++] = arr[j++];
for (i = left; i <= right; i++) arr[i] = temp[i];
return dis;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (i = 0; i < n; i++) cin >> dot[i].first;
for (i = 0; i < n; i++) cin >> dot[i].second;
sort(dot, dot + n);
cout << movingdot(dot, n);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 5, MOD = 1e9 + 7;
pair<long long, long long> a[N];
vector<pair<long long, long long> > tree[4 * N];
void build(long long node, long long st, long long en) {
if (st == en) {
tree[node].push_back({a[st].first, a[st].first});
return;
}
long long mid = (st + en) / 2;
build(2 * node, st, mid);
build(2 * node + 1, mid + 1, en);
long long x = tree[2 * node].size();
long long y = tree[2 * node + 1].size();
long long i = 0, j = 0;
while (i < x && j < y) {
if (tree[2 * node][i].first < tree[2 * node + 1][j].first) {
tree[node].push_back(tree[2 * node][i]);
i++;
} else {
tree[node].push_back(tree[2 * node + 1][j]);
j++;
}
}
while (i < x) {
tree[node].push_back(tree[2 * node][i]);
i++;
}
while (j < y) {
tree[node].push_back(tree[2 * node + 1][j]);
j++;
}
long long z = x + y;
tree[node][z - 1].second = tree[node][z - 1].first;
for (long long k = z - 2; k >= 0; k--) {
tree[node][k].second = tree[node][k + 1].second + tree[node][k].first;
}
}
pair<long long, long long> query(long long node, long long st, long long en,
long long l, long long r, long long val) {
if (l > en || r < st) return {0, 0};
if (l <= st && en <= r) {
long long lo = 0, hi = tree[node].size() - 1, idx = MOD;
while (lo <= hi) {
long long m = (lo + hi) / 2;
if (tree[node][m].first > val) {
idx = min(idx, m);
hi = m - 1;
} else
lo = m + 1;
}
if (idx == MOD)
return {0, 0};
else
return {tree[node][idx].second, tree[node].size() - idx};
}
long long mid = (st + en) / 2;
long long ans = 0;
pair<long long, long long> p1 = query(2 * node, st, mid, l, r, val);
pair<long long, long long> p2 = query(2 * node + 1, mid + 1, en, l, r, val);
pair<long long, long long> p;
p.first = p1.first + p2.first;
p.second = p1.second + p2.second;
return p;
}
bool compare(pair<long long, long long> p1, pair<long long, long long> p2) {
if (p1.second == p2.second) return p1.first > p2.first;
return p1.second > p2.second;
}
void solve() {
long long n;
cin >> n;
for (long long i = 0; i < n; i++) cin >> a[i].first;
for (long long i = 0; i < n; i++) cin >> a[i].second;
sort(a, a + n, compare);
build(1, 0, n - 1);
long long ans = 0;
for (long long i = 1; i < n; i++) {
pair<long long, long long> p = query(1, 0, n - 1, 0, i - 1, a[i].first);
long long temp = abs(p.first - p.second * a[i].first);
ans += temp;
}
cout << ans << "\n";
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
template <typename Monoid>
struct SegmentTree {
typedef function<Monoid(Monoid, Monoid)> F;
int n;
F f;
Monoid id;
vector<Monoid> dat;
SegmentTree(int n_, F f, Monoid id) : f(f), id(id) { init(n_); }
void init(int n_) {
n = 1;
while (n < n_) n <<= 1;
dat.assign(n << 1, id);
}
void build(const vector<Monoid> &v) {
for (int i = 0; i < v.size(); ++i) dat[i + n] = v[i];
for (int i = n - 1; i; --i) dat[i] = f(dat[i << 1 | 0], dat[i << 1 | 1]);
}
void update(int k, Monoid x) {
dat[k += n] = x;
while (k >>= 1) dat[k] = f(dat[k << 1 | 0], dat[k << 1 | 1]);
}
Monoid query(int a, int b) {
if (a >= b) return id;
Monoid vl = id, vr = id;
for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
if (l & 1) vl = f(vl, dat[l++]);
if (r & 1) vr = f(dat[--r], vr);
}
return f(vl, vr);
}
Monoid operator[](int i) { return dat[i + n]; }
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<long long> x(n), v(n);
for (int i = 0; i < n; ++i) cin >> x[i];
for (int i = 0; i < n; ++i) cin >> v[i];
vector<vector<pair<long long, long long>>> ps(2);
for (int i = 0; i < n; ++i) {
if (0 <= v[i])
ps[0].emplace_back(v[i], x[i]);
else
ps[1].emplace_back(-v[i], -x[i]);
}
vector<long long> vs;
vector<pair<long long, int>> xs;
auto f = [](pair<long long, int> a, pair<long long, int> b) {
return pair<long long, int>{a.first + b.first, a.second + b.second};
};
SegmentTree<pair<long long, int>> seg(n, f, {0, 0});
vector<pair<long long, int>> initializer(n, {0, 0});
long long ans = 0;
for (int i = 1; i >= 0; --i) {
sort(ps[i].begin(), ps[i].end());
int m = ps[i].size();
vs.clear();
xs.clear();
for (int j = 0; j < m; ++j) {
vs.emplace_back(ps[i][j].first);
xs.emplace_back(ps[i][j].second, j);
}
if (!i) seg.build(initializer);
sort(xs.begin(), xs.end());
for (int j = 0; j < m; ++j) seg.update(xs[j].second, {xs[j].first, 1});
for (int j = 0; j < m; ++j) {
int s = lower_bound(vs.begin(), vs.end(), ps[i][xs[j].second].first) -
vs.begin();
auto p = seg.query(s, m);
ans += p.first - xs[j].first * p.second;
seg.update(xs[j].second, {0, 0});
}
}
int t = ps[0].size();
vector<long long> sum(t + 1, 0);
for (int i = 0; i < t; ++i) {
sum[i + 1] = sum[i] + xs[i].first;
vs[i] = xs[i].first;
}
for (int i = 0; i < ps[1].size(); ++i) {
int b = upper_bound(vs.begin(), vs.end(), -ps[1][i].second) - vs.begin();
ans += sum[t] - sum[b] + ps[1][i].second * (t - b);
}
cout << ans << '\n';
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, i;
cin >> n;
pair<long long, long long> p[n];
long long a[n];
for (i = 0; i < n; i++) {
cin >> a[i];
p[i].second = a[i];
}
for (i = 0; i < n; i++) cin >> p[i].first;
sort(a, a + n);
sort(p, p + n);
map<long long, long long> mp;
long long ans = 0;
for (i = 0; i < n; i++) {
ans += a[i] * (2 * i + 1 - n);
mp[a[i]] = i;
}
for (i = 0; i < n; i++) {
ans -= p[i].second * (mp[p[i].second] - i);
}
cout << ans << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
using namespace std;
inline int read() {
int x = 0, neg = 1;
char op = getchar();
while (!isdigit(op)) {
if (op == '-') neg = -1;
op = getchar();
}
while (isdigit(op)) {
x = 10 * x + op - '0';
op = getchar();
}
return neg * x;
}
inline void print(int x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
const int N = 200005;
struct ele {
int x;
long long v;
friend bool operator<(const ele &a, const ele &b) { return a.x < b.x; }
} a[N];
int b[N], tot;
int n;
struct Bitcount {
int c[N];
void add(int x, int v) {
while (x < N) {
c[x] += v;
x += (x & -x);
}
}
int qry(int x) {
int ret = 0;
if (x < 0) return 0;
while (x > 0) {
ret += c[x];
x -= (x & -x);
}
return ret;
}
int query(int l, int r) { return qry(r) - qry(l - 1); }
} bitc;
struct Bitsum {
long long c[N];
void add(int x, long long v) {
while (x < N) {
c[x] += v;
x += (x & -x);
}
}
long long qry(int x) {
long long ret = 0;
if (x < 0) return 0;
while (x > 0) {
ret += c[x];
x -= (x & -x);
}
return ret;
}
long long query(int l, int r) { return qry(r) - qry(l - 1); }
} bits;
int main() {
n = read();
for (register int i = 1; i <= n; i++) {
a[i].x = read();
}
for (register int i = 1; i <= n; i++) {
a[i].v = read();
b[++tot] = a[i].v;
}
sort(b + 1, b + tot + 1);
tot = unique(b + 1, b + tot + 1) - (b + 1);
sort(a + 1, a + n + 1);
for (register int i = 1; i <= n; i++) {
a[i].v = lower_bound(b + 1, b + tot + 1, a[i].v) - b;
}
long long ans = 0ll;
for (register int i = n; i >= 1; i--) {
long long possum = bits.query(a[i].v, N - 1);
long long posnum = bitc.query(a[i].v, N - 1);
ans += possum - 1ll * a[i].x * posnum;
bits.add(a[i].v, a[i].x);
bitc.add(a[i].v, 1);
}
printf("%lld\n", ans);
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author KharYusuf
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FMovingPoints solver = new FMovingPoints();
solver.solve(1, in, out);
out.close();
}
static class FMovingPoints {
public void solve(int testNumber, FastReader s, PrintWriter w) {
int n = s.nextInt(), MX = (int) 1e8;
int[][] x = new int[n][2];
for (int i = 0; i < n; i++) x[i][0] = s.nextInt();
TreeSet<Integer> p = new TreeSet<>(), ne = new TreeSet<>();
TreeMap<Integer, Integer> po = new TreeMap<>(), nee = new TreeMap<>();
for (int i = 0; i < n; i++) {
x[i][1] = s.nextInt();
if (x[i][1] > 0) p.add(x[i][1]);
else if (x[i][1] < 0) ne.add(x[i][1] + MX);
}
int cnt = 0;
for (int i : p) po.put(i, cnt++);
cnt = 0;
for (int i : ne) nee.put(i, cnt++);
func.sortbyColumn(x, 0);
long ans = 0, cntneg = 0, cntz = 0, cneg = 0, cz = 0;
bit pos = new bit(p.size()), neg = new bit(nee.size());
bit poscnt = new bit(p.size()), negcnt = new bit(nee.size());
for (int i = 0; i < n; i++) {
if (x[i][1] > 0) {
ans += x[i][0] * cntneg - cneg;
ans += x[i][0] * cntz - cz;
int cur = po.get(x[i][1]);
ans += poscnt.query(cur) * x[i][0] - pos.query(cur);
poscnt.modify(cur, 1);
pos.modify(cur, x[i][0]);
} else if (x[i][1] < 0) {
cntneg++;
cneg += x[i][0];
int cur = nee.get(MX + x[i][1]);
ans += negcnt.query(cur) * x[i][0] - neg.query(cur);
negcnt.modify(cur, 1);
neg.modify(cur, x[i][0]);
} else {
cntz++;
cz += x[i][0];
ans += x[i][0] * cntneg - cneg;
ans += x[i][0] * cntz - cz;
}
}
w.println(ans);
}
public class bit {
public int n;
public long[] t;
public bit(int n) {
t = new long[n];
this.n = n;
}
public void modify(int ind, long val) {
for (; ind < n; ind = ind | (++ind)) t[ind] += val;
}
public long query(int ind) {
long sum = 0;
for (; ind >= 0; ind = (ind & (++ind)) - 1) sum += t[ind];
return sum;
}
}
}
static class func {
public static void sortbyColumn(int[][] arr, final int col) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(final int[] entry1, final int[] entry2) {
if (entry1[col] > entry2[col]) return 1;
if (entry1[col] < entry2[col]) return -1;
return 0;
}
});
}
}
static class bit {
public int n;
public int[] t;
public bit(int n) {
t = new int[n];
this.n = n;
}
public bit(int[] a, int n) {
t = new int[n];
this.n = n;
for (int i = 0; i < n; i++) {
modify(i, a[i]);
}
}
public void modify(int ind, int val) {
for (; ind < n; ind = ind | (++ind)) t[ind] += val;
}
public int query(int ind) {
int sum = 0;
for (; ind >= 0; ind = (ind & (++ind)) - 1) sum += t[ind];
return sum;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
java
|
import java.util.*;
public class Main
{
static class comp implements Comparator<long []>
{
public int compare(long a1[],long a2[])
{
if(a1[1]!=a2[1])
{
if(a1[1]>a2[1])
return 1;
else
return -1;
}
if(a1[0]>a2[0])
return 1;
else
return -1;
}
}
public static void update(long val,int in,long b[],int i,int cnt[])
{
for(int j=i;j<in;j+=(j&(-j)))
{
b[j]+=val;
cnt[j]++;
}
}
public static long query(int i,long b[],long val,int cnt[])
{
long sum=0;
for(int j=i-1;j>0;j-=(j&(-j)))
sum=sum+val*cnt[j]-b[j];
return sum;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long arr[][]=new long[n][2];
TreeSet<Long> ts=new TreeSet<>();
for(int i=0;i<n;i++)
{
arr[i][0]=sc.nextLong();
ts.add(arr[i][0]);
}
TreeMap<Long,Integer> ind=new TreeMap<>();
long b[]=new long[ts.size()+1];
int cnt[]=new int[ts.size()+1];
int in=1;
while(!ts.isEmpty())
{
long node=ts.pollFirst();
ind.put(node,in);
in++;
}
for(int i=0;i<n;i++)
arr[i][1]=sc.nextLong();
Arrays.sort(arr,new comp());
long ans=0;
for(int i=0;i<n;i++)
{
ans=ans+query(ind.get(arr[i][0]),b,arr[i][0],cnt);
update(arr[i][0],in,b,ind.get(arr[i][0]),cnt);
}
System.out.println(ans);
}
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long maxn = 6e6;
const long long inf = 1e9;
const long long maxv = 2e8 + 100;
void init() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
struct point {
long long x, v;
point() {}
};
vector<point> foo;
unordered_map<long long, pair<long long, long long>> tree(maxn);
const long long toadd = 1e8 + 1;
inline long long f(long long i) { return i & (i + 1); }
void inc(long long st) {
long long ind = foo[st].v + toadd;
while (ind < maxv) {
tree[ind].first++;
tree[ind].second += foo[st].x;
ind |= (ind + 1);
}
}
pair<long long, long long> operator+(const pair<long long, long long> &a,
const pair<long long, long long> &b) {
return {a.first + b.first, a.second + b.second};
}
pair<long long, long long> prefsum(long long ind) {
pair<long long, long long> res = {0, 0};
while (ind >= 0) {
res = res + tree[ind];
ind = f(ind) - 1;
}
return res;
}
int main() {
init();
tree.rehash(maxn);
long long n;
cin >> n;
foo.resize(n);
for (long long i = 0; i < n; i++) {
cin >> foo[i].x;
}
for (long long i = 0; i < n; i++) {
cin >> foo[i].v;
}
sort(foo.begin(), foo.end(),
[&](point &p1, point &p2) { return p1.x < p2.x; });
long long ans = 0;
for (long long i = 0; i < n; i++) {
auto cur = prefsum(foo[i].v + toadd);
ans += (cur.first * foo[i].x - cur.second);
inc(i);
}
cout << ans << endl;
return 0;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
python3
|
# BIT
def add(bit, x, v):
while x < len(bit):
bit[x] += v
x += x & (-x)
def query(bit, x):
ans = 0
while x > 0:
ans += bit[x]
x -= x & (-x)
return ans
def relabel(arr):
srt = sorted(set(arr))
mp = {v:k for k, v in enumerate(srt, 1)}
arr = [mp[a] for a in arr]
return arr
# main
n = int(input())
x = list(map(int, input().split()))
v = relabel(list(map(int, input().split())))
arr = sorted(list(zip(x, v)));
ans = 0
bitSum = [0]*(n+1)
bitCnt = [0]*(n+1)
for x, v in arr:
ans += query(bitCnt, v)*x - query(bitSum, v)
add(bitSum, v, x)
add(bitCnt, v, 1)
print(ans)
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1000007, inf = 0x3f3f3f3f;
int x[N], v[N];
pair<long long, int> seg[N + N];
pair<long long, int> soma(pair<long long, int> x, pair<long long, int> y) {
return pair<long long, int>(x.first + y.first, x.second + y.second);
}
pair<long long, int> query(int l, int r) {
pair<long long, int> tot = pair<long long, int>(0ll, 0);
for (l += N, r += N; l < r; l >>= 1, r >>= 1) {
if (l & 1) tot = soma(tot, seg[l++]);
if (r & 1) tot = soma(tot, seg[--r]);
}
return tot;
}
void update(int p, int val) {
p += N;
for (seg[p] = pair<long long, int>(seg[p].first + val, seg[p].second + 1);
p > 1; p >>= 1) {
seg[p >> 1] = soma(seg[p], seg[p ^ 1]);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
vector<int> vec;
for (int i = 0; i < n; ++i) {
cin >> v[i];
vec.push_back(v[i]);
}
sort(vec.begin(), vec.end());
vec.erase(unique(vec.begin(), vec.end()), vec.end());
vector<int> id(n);
iota(id.begin(), id.end(), 0);
sort(id.begin(), id.end(), [](int i, int j) { return x[i] < x[j]; });
long long ans = 0;
for (int i : id) {
int j = lower_bound(vec.begin(), vec.end(), v[i]) - vec.begin();
long long sx;
int cnt;
tie(sx, cnt) = query(0, j + 1);
ans += (long long)x[i] * cnt - sx;
update(j, x[i]);
}
memset(seg, 0, sizeof seg);
reverse(id.begin(), id.end());
for (int i : id) {
int j = lower_bound(vec.begin(), vec.end(), v[i]) - vec.begin();
long long sx;
int cnt;
tie(sx, cnt) = query(j, vec.size());
ans += sx - (long long)x[i] * cnt;
update(j, x[i]);
}
cout << ans / 2 << endl;
}
|
1311_F. Moving Points
|
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. 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 x_i + t ⋅ v_i.
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 ⋅ 10^5) — the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 ≤ v_i ≤ 10^8), where v_i 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
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
|
{
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
}
|
{
"input": [],
"output": []
}
|
CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long int tree[800005], sree[800005];
struct sc {
long long int a, b;
};
bool comp(sc x, sc y) {
if (x.a < y.a) return 1;
return 0;
}
void update(long long int node, long long int s, long long int e,
long long int ind, long long int val) {
if (s == e) {
tree[node] += val;
sree[node] += 1;
} else {
long long int m = (s + e) / 2;
if (s <= ind && ind <= m)
update(2 * node, s, m, ind, val);
else
update(2 * node + 1, m + 1, e, ind, val);
tree[node] = tree[2 * node] + tree[2 * node + 1];
sree[node] = sree[2 * node] + sree[2 * node + 1];
}
}
long long int q_sum(long long int node, long long int s, long long int e,
long long int l, long long int r) {
if (r < s || e < l) return 0;
if (l <= s && e <= r) return tree[node];
long long int m = (s + e) / 2;
long long int ans1 = q_sum(2 * node, s, m, l, r);
long long int ans2 = q_sum(2 * node + 1, m + 1, e, l, r);
long long int ans = ans1 + ans2;
return ans;
}
long long int q_cnt(long long int node, long long int s, long long int e,
long long int l, long long int r) {
if (r < s || e < l) return 0;
if (l <= s && e <= r) return sree[node];
long long int m = (s + e) / 2;
long long int ans1 = q_cnt(2 * node, s, m, l, r);
long long int ans2 = q_cnt(2 * node + 1, m + 1, e, l, r);
long long int ans = ans1 + ans2;
return ans;
}
int main() {
long long int n, i, j, ans = 0;
cin >> n;
sc e[n + 1];
long long int c[n + 1];
for (i = 1; i <= n; ++i) {
cin >> e[i].a;
}
for (i = 1; i <= n; ++i) {
cin >> e[i].b;
c[i] = e[i].b;
}
sort(e + 1, e + n + 1, comp);
sort(c + 1, c + n + 1);
long long int l = 1;
map<long long int, long long int> mp;
for (i = 1; i <= n; ++i)
if (mp.find(c[i]) == mp.end()) mp[c[i]] = l++;
for (i = n; i >= 1; --i) {
update(1, 1, n, mp[e[i].b], e[i].a);
ans = ans + (q_sum(1, 1, n, mp[e[i].b], l) -
(q_cnt(1, 1, n, mp[e[i].b], l) * e[i].a));
}
cout << ans << "\n";
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.