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
|
python3
|
class SegmentTree():
def __init__(self,N,func,initialRes=0):
self.f=func
self.N=N
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
st=getSumSegTree(n) #for sum of xes
stCnts=getSumSegTree(n) #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
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int n, tot;
long long ans, ans1, ans2;
struct dot {
long long x, v, nv;
} a[maxn];
struct node {
long long cnt, d;
} T[maxn * 4];
bool cmp1(dot x, dot y) { return x.v < y.v; }
bool cmp2(dot x, dot y) { return x.x < y.x; }
void pushup(int x) {
T[x].cnt = T[(x << 1)].cnt + T[(x << 1 | 1)].cnt;
T[x].d = T[(x << 1)].d + T[(x << 1 | 1)].d;
}
void insert(int x, int l, int r, int pos, int p) {
if (l == r) {
T[x].cnt++;
T[x].d += a[p].x;
return;
}
int mid = (l + r) >> 1;
if (pos <= mid)
insert((x << 1), l, mid, pos, p);
else
insert((x << 1 | 1), mid + 1, r, pos, p);
pushup(x);
}
void query(int x, int l, int r, int sj, int tj) {
if (sj <= l && r <= tj) {
ans1 += T[x].cnt;
ans2 += T[x].d;
return;
}
int mid = (l + r) >> 1;
if (sj <= mid) query((x << 1), l, mid, sj, tj);
if (mid + 1 <= tj) query((x << 1 | 1), mid + 1, r, sj, tj);
}
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);
sort(a + 1, a + n + 1, cmp1);
tot = 0;
a[1].nv = ++tot;
for (int i = 2; i <= n; i++) {
if (a[i].v == a[i - 1].v)
a[i].nv = tot;
else
a[i].nv = ++tot;
}
sort(a + 1, a + n + 1, cmp2);
ans = 0;
for (int i = 1; i <= n; i++) {
ans1 = ans2 = 0;
query(1, 1, tot, 1, a[i].nv);
ans += ans1 * a[i].x - ans2;
insert(1, 1, tot, a[i].nv, i);
}
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>
template <class C>
inline void log_c(const C& c) {}
template <class C>
inline int sz(const C& c) {
return static_cast<int>(c.size());
}
using namespace std;
using pii = pair<int, int>;
using num = int64_t;
using pll = pair<num, num>;
const std::string eol = "\n";
const int max_x = 100000000;
using It = vector<int>::iterator;
int64_t min_distance_sum(It begin, It end, It tmp_begin) {
if (next(begin) == end) return 0;
int64_t left_count = distance(begin, end) / 2;
It mid = next(begin, left_count);
const int64_t ans_left = min_distance_sum(begin, mid, tmp_begin);
const int64_t ans_right =
min_distance_sum(mid, end, next(tmp_begin, left_count));
int64_t ans_cross = 0;
It it1 = begin;
It it2 = mid;
It tmp = tmp_begin;
int64_t left_sum = 0;
while (it1 != mid && it2 != end) {
if (*it1 < *it2) {
left_sum += *it1;
*tmp++ = *it1++;
} else {
ans_cross += static_cast<int64_t>(*it2) * distance(begin, it1) - left_sum;
*tmp++ = *it2++;
}
}
copy(it1, mid, tmp);
while (it2 != end) {
ans_cross += static_cast<int64_t>(*it2) * left_count - left_sum;
*tmp++ = *it2++;
}
copy(tmp_begin, next(tmp_begin, distance(begin, end)), begin);
return ans_left + ans_right + ans_cross;
}
int main() {
std::ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<pii> data(n);
for (int k = 0; k < (n); ++k) cin >> data[k].second;
for (int k = 0; k < (n); ++k) cin >> data[k].first;
sort(begin(data), end(data));
vector<int> x(n), tmp(n);
for (int k = 0; k < (n); ++k) x[k] = data[k].second;
cout << min_distance_sum(begin(x), end(x), tmp.begin()) << eol;
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[] = {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};
struct FenwickTree {
vector<long long int> bit;
int n;
FenwickTree(int n) {
this->n = n;
bit.assign(n, 0);
}
long long int sum(int r) {
long long int ret = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) ret += bit[r];
return ret;
}
long long int sum(int l, int r) { return sum(r) - sum(l - 1); }
void add(int idx, int delta) {
for (; idx < n; idx = idx | (idx + 1)) bit[idx] += delta;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<pair<int, int> > vec(n + 1);
vector<int> aux;
vec.resize(n);
for (int i = 0; i < n; i++) cin >> vec[i].first;
for (int i = 0; i < n; i++) cin >> vec[i].second;
sort(vec.begin(), vec.end());
FenwickTree cnt(n), soma(n);
for (auto i : vec) aux.push_back(i.second);
sort(aux.begin(), aux.end());
long long int ans = 0;
for (auto i : vec) {
int pos = lower_bound(aux.begin(), aux.end(), i.second) - aux.begin();
ans += (cnt.sum(pos) * i.first) - soma.sum(pos);
cnt.add(pos, 1);
soma.add(pos, i.first);
}
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
|
python3
|
#Pye
from os import path
from sys import stdin, stdout
from bisect import bisect_left
if path.exists('inp.txt'): stdin = open("inp.txt", "r")
maxn = 200005
a = []; b = []; fen = [(0, 0) for i in range(maxn)]
res = 0
n = int(stdin.readline())
def update(x, val):
global fen
while x > 0:
fen[x] = (fen[x][0] + val, fen[x][1] + 1)
x -= x & (-x)
def get(x, val):
global n, fen
A = 0; B = 0
while x < n+2:
A += fen[x][0]
B += fen[x][1]
x += x & (-x)
return A - B * val
af = list(map(int, stdin.readline().split()))
ad = list(map(int, stdin.readline().split()))
for i in range(n): a.append((af[i], ad[i])); b.append(ad[i])
a.sort()
b.sort()
for i in range(n): a[i] = (a[i][0], bisect_left(b, a[i][1]) + 1)
for i in range(n-1, -1, -1):
res += get(a[i][1], a[i][0])
update(a[i][1], a[i][0])
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;
using ll = long long;
template <class T, class U>
using Pa = pair<T, U>;
template <class T>
using vec = vector<T>;
template <class T>
using vvec = vector<vec<T>>;
template <typename Monoid, typename F>
class SegmentTree {
private:
int sz;
vector<Monoid> seg;
const F op;
const Monoid e;
public:
SegmentTree(int n, const F op, const Monoid &e) : op(op), e(e) {
sz = 1;
while (sz <= n) sz <<= 1;
seg.assign(2 * sz, e);
}
void set(int k, const Monoid &x) { seg[k + sz] = x; }
void build() {
for (int i = sz - 1; i > 0; i--) {
seg[i] = op(seg[2 * i], seg[2 * i + 1]);
}
}
void update(int k, const Monoid &x) {
k += sz;
seg[k] = x;
while (k >>= 1) {
seg[k] = op(seg[2 * k], seg[2 * k + 1]);
}
}
Monoid query(int l, int r) {
Monoid L = e, R = e;
for (l += sz, r += sz; l < r; l >>= 1, r >>= 1) {
if (l & 1) L = op(L, seg[l++]);
if (r & 1) R = op(seg[--r], R);
}
return op(L, R);
}
Monoid operator[](const int &k) const { return seg[k + sz]; }
};
template <class T>
class Compress {
map<T, int> idx;
map<int, T> value;
vector<T> cmp;
public:
int N;
Compress(vector<T> v) {
for (auto &x : v) cmp.push_back(x);
sort(cmp.begin(), cmp.end());
cmp.erase(unique(cmp.begin(), cmp.end()), cmp.end());
N = cmp.size();
for (int i = 0; i < N; i++) idx[cmp[i]] = i;
}
int id(T val) { return idx[val]; }
T val(int id) { return cmp[id]; }
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N;
cin >> N;
vec<ll> X(N), V(N);
for (int i = 0; i < N; i++) cin >> X[i];
for (int i = 0; i < N; i++) cin >> V[i];
Compress<ll> cmp(X);
vec<ll> P(N + 1), M(N + 1), Z(N + 1);
vec<ll> PC(N + 1), MC(N + 1), ZC(N + 1);
for (int i = 0; i < N; i++) {
if (V[i] > 0) {
P[cmp.id(X[i])] += X[i];
PC[cmp.id(X[i])]++;
} else if (V[i] < 0) {
M[cmp.id(X[i])] += X[i];
MC[cmp.id(X[i])]++;
} else {
Z[cmp.id(X[i])] += X[i];
ZC[cmp.id(X[i])]++;
}
}
for (int i = 0; i < N; i++) {
M[i + 1] += M[i];
MC[i + 1] += MC[i];
Z[i + 1] += Z[i];
ZC[i + 1] += ZC[i];
}
for (int i = N - 1; i >= 0; i--) {
P[i] += P[i + 1];
PC[i] += PC[i + 1];
}
struct state {
ll sum, cnt;
};
auto op = [](state L, state R) {
return (state){L.sum + R.sum, L.cnt + R.cnt};
};
SegmentTree<state, decltype(op)> seg(N, op, (state){0, 0});
vec<int> idx(N);
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&](int i, int j) {
return (V[i] != V[j] ? V[i] > V[j] : X[i] > X[j]);
});
ll ans = 0;
for (int i = 0; i < N; i++) {
int id = idx[i];
if (V[id] <= 0) break;
int xid = cmp.id(X[id]);
ans += MC[xid] * X[id] - M[xid];
state res = seg.query(xid, N);
ans += res.sum - X[id] * res.cnt;
seg.update(xid, {X[id], 1});
}
sort(idx.begin(), idx.end(), [&](int i, int j) {
return (V[i] != V[j] ? V[i] < V[j] : X[i] < X[j]);
});
for (int i = 0; i < N; i++) seg.set(i, {0, 0});
seg.build();
for (int i = 0; i < N; i++) {
int id = idx[i];
if (V[id] >= 0) continue;
int xid = cmp.id(X[id]);
state res = seg.query(0, xid);
ans += X[id] * res.cnt - res.sum;
seg.update(xid, {X[id], 1});
}
for (int i = 0; i < N; i++)
if (V[i] == 0) {
int xid = cmp.id(X[i]);
ans += MC[xid] * X[i] - M[xid];
ans += P[xid] - PC[xid] * X[i];
ans += ZC[xid] * X[i] - Z[xid];
}
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;
const long long int N = 2e5 + 2;
struct Fenwick {
long long int BIT[N] = {};
void update(long long int idx, long long int val) {
for (long long int i = idx; i < N; i += (i & -i)) {
BIT[i] += val;
}
}
long long int query(long long int k) {
long long int sum = 0;
for (long long int i = k; i > 0; i -= (i & -i)) {
sum += BIT[i];
}
return sum;
}
};
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long int n;
cin >> n;
long long int x[n + 1], v[n + 1];
vector<pair<long long int, long long int> > vp;
for (long long int i = 1; i <= n; i++) cin >> x[i];
vector<pair<long long int, long long int> > rr;
for (long long int i = 1; i <= n; i++) {
cin >> v[i];
vp.push_back({x[i], v[i]});
}
sort(vp.begin(), vp.end());
for (long long int i = 0; i < n; i++) {
rr.push_back({vp[i].second, i});
}
sort(rr.begin(), rr.end());
long long int rank = 1;
for (auto it : rr) {
long long int idx = it.second;
vp[idx].second = rank++;
}
long long int ans = 0;
Fenwick ob1, ob2;
long long int leftLess[n + 5], rightBade[n + 5];
for (long long int i = 0; i < n; i++) {
long long int vel = vp[i].second;
leftLess[i] = ob1.query(vel - 1);
ob1.update(vel, 1);
}
for (long long int i = n - 1; i >= 0; i--) {
long long int vel = vp[i].second;
long long int total = n - 1 - i;
long long int less = ob2.query(vel - 1);
rightBade[i] = total - less;
ob2.update(vel, 1);
}
for (long long int i = 0; i < n; i++) {
long long int val = vp[i].first;
ans += val * (leftLess[i] - rightBade[i]);
}
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 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() {
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 maxn = 500007;
long long n, C1[maxn], C2[maxn];
long long ans, p1[maxn], p2[maxn];
pair<long long, long long> fk[maxn];
bool cmp2(long long u, long long v) {
if (fk[u].second < fk[v].second) {
return 1;
} else {
if (fk[u].second == fk[v].second && fk[u].first > fk[v].first) return 1;
}
return 0;
}
long long lowbit(long long u) { return u & (-u); }
void update(long long u, long long w) {
for (long long i = u; i <= n; i += lowbit(i)) C1[i] += w, C2[i] += 1;
}
pair<long long, long long> query(long long u) {
long long ans = 0, ret = 0;
for (long long i = u; i > 0; i -= lowbit(i)) ans += C1[i], ret += C2[i];
return {ans, ret};
}
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> fk[i].second;
p1[i] = i;
}
for (int i = 1; i <= n; ++i) {
cin >> fk[i].first;
p2[i] = i;
}
sort(fk + 1, fk + n + 1);
sort(p1 + 1, p1 + n + 1, cmp2);
for (int i = 1; i <= n; ++i) {
p2[p1[i]] = i;
}
for (int i = 1; i <= n; ++i) {
update(p2[i], fk[i].second);
pair<long long, long long> ret = query(p2[i]);
ans -= ret.first;
ans += ret.second * fk[i].second;
}
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.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class F_Round_624_Div3 {
public static long MOD = 1000000007;
static int[][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[][] data = new int[n][2];
int max = n + 2;
FT total = new FT(max);
FT count = new FT(max);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < n; j++) {
data[j][i] = in.nextInt();
}
}
Arrays.sort(data, (a, b) -> Integer.compare(a[0], b[0]));
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(data[i][0]);
data[i][0] = i + 1;
}
Arrays.sort(data, (a, b) -> {
if (a[1] != b[1]) {
return Integer.compare(a[1], b[1]);
}
return Integer.compare(a[0], b[0]);
});
long result = 0;
for (int[] a : data) {
long c = count.get(a[0]);
long t = total.get(a[0]);
//System.out.println(Arrays.toString(a) + " " + c + " " + t);
result += c * list.get(a[0] - 1) - t;
total.update(a[0], list.get(a[0] - 1));
count.update(a[0], 1);
}
out.println(result);
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
if (x != o.x) {
return Integer.compare(x, o.x);
}
return Integer.compare(y, o.y);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution{
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt-->0) {
int n = fs.nextInt();
int[][] arr = new int[n][2];
for(int i=0;i<n;i++ ) {
arr[i][0] = fs.nextInt();
}
for(int i=0;i<n;i++) {
arr[i][1] = fs.nextInt();
}
//Randomizig the arr array
for(int i=0;i<n;i++) {
int ri = random.nextInt(n);
int[] temp = arr[i]; arr[i] = arr[ri]; arr[ri] = temp;
}
Arrays.sort(arr, (x, y) -> x[0]-y[0]);
int[] p = new int[n];
for(int i=0;i<n;i++) {
p[i] = arr[i][1];
}
ruffleSort(p);
Ftree ft1 = new Ftree(n);
Ftree ft2 = new Ftree(n);
long ans = 0;
for(int i=n-1;i>=0;i--) {
int ind = lowerbound(p, arr[i][1]);
ans += (ft1.query(n-1)-ft1.query(ind-1)) - (ft2.query(n-1)-ft2.query(ind-1))*(arr[i][0]);
ft1.update(ind, arr[i][0]);
ft2.update(ind, 1);
}
out.println(ans);
}
out.close();
}
static class Ftree{
long[] bit;
int n;
Ftree(int n){
this.n = n;
bit = new long[n+1];
}
void update(int ind, int val) {
ind++;
while(ind<=n) {
bit[ind] += val;
ind += ind&(-ind);
}
}
long query(int ind) {
ind++;
long sum = 0;
while(ind>0) {
sum += bit[ind];
ind -= ind&(-ind);
}
return sum;
}
}
static int lowerbound(int[] arr, int x) {
int l = 0;
int r= arr.length;
while(l<r) {
int mid = (l+r)/2;
if(arr[mid]>=x) r = mid;
else l = mid+1;
}
return r;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[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 N = 200000;
long long BIT1[200001];
long long cnt1[200001];
map<long long, long long> r, l;
pair<long long, long long> arr[200001];
int n;
void upd1(long long idx, long long val) {
for (; idx <= N; idx = (idx | (idx + 1))) {
BIT1[idx] += val;
cnt1[idx]++;
}
}
pair<long long, long long> query1(int idx) {
if (idx < 0) return {0, 0};
long long sum = 0;
int ct = 0;
for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {
sum += BIT1[idx];
ct += cnt1[idx];
}
return {sum, ct};
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) cin >> arr[i].first;
for (int i = 1; i <= n; i++) cin >> arr[i].second;
sort(arr + 1, arr + n + 1);
for (int i = 1; i <= n; i++) r[arr[i].second] = 0;
long long ind = 1;
for (auto &it : r) {
it.second = ind;
ind++;
}
long long ans = 0;
for (int i = 1; i <= n; i++) {
long long vel = r[arr[i].second];
pair<long long, long long> p = query1(vel);
ans += (p.second) * (arr[i].first);
ans -= p.first;
upd1(vel, arr[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
|
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
class RangeMinimumQuery:
def __init__(self, n, inf=float("inf")):
self.n0 = 2**(n-1).bit_length()
self.inf = inf
self.data = [self.inf]*(2*self.n0)
self.cnt = [0]*(2*self.n0)
def query(self, l,r):
l += self.n0
r += self.n0
res = 0
cnt = 0
while l < r:
if r&1:
r -= 1
res += self.data[r-1]
cnt += self.cnt[r-1]
if l&1:
res += self.data[l-1]
cnt += self.cnt[l-1]
l += 1
l >>=1
r >>=1
return res, cnt
def update(self, i, x):
i += self.n0-1
self.data[i] += x
self.cnt[i] += 1
while i:
i = ~-i//2
self.data[i] = self.data[2*i+1] + self.data[2*i+2]
self.cnt[i] = self.cnt[2*i+1] + self.cnt[2*i+2]
n = int(input())
xs = list(map(int, input().split()))
vs = list(map(int, input().split()))
xv = [[x,v] for x,v in zip(xs,vs)]
xv.sort()
d = sorted(set(vs))
dd = {j:i for i,j in enumerate(d)}
m = len(dd)
RSQ = RangeMinimumQuery(m, 0)
ans = 0
for x, v in xv:
nv = dd[v]
su, cnt = RSQ.query(0, nv+1)
ans += cnt*x - su
RSQ.update(nv, x)
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
|
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:
temp = sorted(set(v))
mp = {v: k for k, v in enumerate(temp, 1)}
# Solve the problem:
cnt = Fenwick_tree(n)
sum = Fenwick_tree(n)
res, i = 0, 0
for i in range(n):
a[i].v = mp[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
|
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<>();
TreeMap<Integer, Integer> po = new TreeMap<>();
for (int i = 0; i < n; i++) {
x[i][1] = s.nextInt();
p.add(x[i][1]);
}
int cnt = 0;
for (int i : p) po.put(i, cnt++);
func.sortbyColumn(x, 0);
long ans = 0;
bit num = new bit(p.size()), numcnt = new bit(p.size());
for (int i = 0; i < n; i++) {
int cur = po.get(x[i][1]);
ans += numcnt.query(cur) * x[i][0] - num.query(cur);
numcnt.modify(cur, 1);
num.modify(cur, x[i][0]);
}
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
|
python3
|
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 2020/3/13
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
def solve(N, X, S):
si = {}
ss = list(sorted(set(S)))
for i, s in enumerate(ss):
si[s] = i
xs = [(x, si[s]) for x, s in zip(X, S)]
xs.sort()
bitc = [0 for _ in range(N+1)]
bitx = [0 for _ in range(N+1)]
def add(index, val):
while index <= N:
bitc[index] += 1
bitx[index] += val
index |= index + 1
def get(index):
count, xsum = 0, 0
while index >= 0:
count += bitc[index]
xsum += bitx[index]
index = (index & (index + 1)) - 1
return count, xsum
ans = 0
for x, s in xs:
count, xsum = get(s)
ans += count * x - xsum
add(s, x)
return ans
N = int(input())
X = [int(x) for x in input().split()]
S = [int(x) for x in input().split()]
print(solve(N, X, S))
|
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 E implements Runnable {
boolean judge = false;
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt();
int[] x = scn.nextIntArray(n);
int[] v = new int[n + 1];
for(int i = 0; i < n; i++) {
v[i] = scn.nextInt();
}
int[] cmpX = scn.compress(Arrays.copyOf(x, n));
int[] cmpV = scn.compress(Arrays.copyOf(v, n + 1));
for(int i = 0; i < n; i++) {
cmpX[i]++;
}
for(int i = 0; i <= n; i++) {
cmpV[i]++;
}
long[] bit = new long[2 * n + 1];
long[] bit2 = new long[2 * n + 1];
int ninf = -(int) 1e9;
int[][] need = new int[n][4];
for(int i = 0; i < n; i++) {
need[i][0] = x[i];
need[i][1] = v[i];
need[i][2] = cmpX[i];
need[i][3] = cmpV[i];
add(bit, need[i][3], need[i][0] - ninf);
add(bit2, need[i][3], 1);
}
Arrays.parallelSort(need, (o1, o2) -> o1[0] - o2[0]);
long ans = 0;
for(int i = 0; i < n; i++) {
long diff = need[i][0] - ninf;
long rv = sum(bit, 2 * n) - sum(bit, need[i][3] - 1);
long pt = sum(bit2, 2 * n) - sum(bit2, need[i][3] - 1);
ans += rv - pt * diff;
add(bit, need[i][3], -(need[i][0] - ninf));
add(bit2, need[i][3], -1);
}
out.println(ans);
}
void add(long[] bit, int ind, long val) {
while (ind < bit.length) {
bit[ind] += val;
ind += ind & (-ind);
}
}
long sum(long[] bit, int ind) {
long rv = 0;
while (ind > 0) {
rv += bit[ind];
ind -= ind & (-ind);
}
return rv;
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null || judge;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new E(), "Main", 1 << 28).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
}
}
|
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 c[200005][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 x, int k) {
long long ret = 0;
for (int i = x; i >= 1; i -= i & -i) ret += c[i][k];
return ret;
}
void update(int x, int y) {
for (int i = x; i <= m; i += i & -i) {
c[i][0]++;
c[i][1] += y;
}
}
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 t = lsh(a[i].v);
ans += query(t, 0) * a[i].x - query(t, 1);
update(t, a[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;
const int inf = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
const long long maxn = 500010;
long long T, n, m, p[maxn], v[maxn], mxval = 0, tree[maxn], cnt[maxn], ans = 0;
struct node {
int pos, val, v;
} a[maxn];
void add(int pos, long long val) {
pos += n;
cnt[pos] += 1;
tree[pos] += val;
while (pos) {
pos /= 2;
cnt[pos] = cnt[pos << 1] + cnt[pos << 1 | 1];
tree[pos] = tree[pos << 1] + tree[pos << 1 | 1];
}
}
pair<long long, long long> sum(int l, int r) {
long long ret = 0, p = 0;
for (l += n - 1, r += n + 1; l ^ r ^ 1; l /= 2, r /= 2) {
if (~l & 1) ret += tree[l ^ 1], p += cnt[l ^ 1];
if (r & 1) ret += tree[r ^ 1], p += cnt[r ^ 1];
}
return make_pair(p, ret);
}
int main() {
scanf("%lld", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i].pos);
for (int i = 1; i <= n; i++) scanf("%d", &a[i].v);
sort(a + 1, a + 1 + n, [](node a, node b) { return a.v < b.v; });
a[1].val = 1;
for (int i = 2; i <= n; i++) {
if (a[i].v > a[i - 1].v)
a[i].val = a[i - 1].val + 1;
else
a[i].val = a[i - 1].val;
}
mxval = a[n].val;
sort(a + 1, a + 1 + n, [](node a, node b) { return a.pos < b.pos; });
memset(tree, 0, sizeof(tree));
memset(cnt, 0, sizeof(cnt));
for (int i = 1; i <= n; i++) {
pair<long long, long long> x = sum(1, a[i].val);
ans += x.first * a[i].pos - x.second;
add(a[i].val, a[i].pos);
}
memset(tree, 0, sizeof(tree));
memset(cnt, 0, sizeof(cnt));
for (int i = n; i >= 1; i--) {
pair<long long, long long> x = sum(a[i].val, mxval);
ans += x.second - x.first * a[i].pos;
add(a[i].val, a[i].pos);
}
printf("%lld\n", ans / 2);
}
|
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 xx,int vv){
x=xx;v=vv;
}
@Override
public int compareTo(pair o) {
// TODO Auto-generated method stub
return x-o.x;
}
}
static class ftree{
int n;
long[]ft;
ftree(int z){
ft=new long[z+1];
n=z;
}
void updatesum(int idx,int k) {
while(idx<=n) {
ft[idx]+=k;
idx+=(idx&(-1*idx));
}
}
long querysum(int idx) {
long sum=0;
while(idx>0) {
sum+=ft[idx];
idx-=(idx&(-1*idx));
}
return sum;
}
}
public static void main(String[] args) throws Exception{
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int[]x=sc.takearr(n);
int[]v=sc.takearr(n);
pair[]in=new pair[n];
Integer[]tmp=new Integer[n];
for(int i=0;i<n;i++) {
tmp[i]=v[i];
}
Arrays.sort(tmp);
for(int i=0;i<n;i++) {
in[i]=new pair(x[i], v[i]);
}
Arrays.sort(in);
HashMap<Integer, Integer>map=new HashMap<Integer, Integer>();
for(int i=0;i<n;i++) {
map.put(tmp[i], i+1);
}
long ans=0;
ftree ftOcc=new ftree(n+7);
ftree ftSum=new ftree(n+7);
for(int i=0;i<n;i++) {
int curx=in[i].x,curv=in[i].v;
long cnt=ftOcc.querysum(map.get(curv));
long sum=ftSum.querysum(map.get(curv));
ans+=(curx*1l*cnt-sum);
ftOcc.updatesum(map.get(curv), 1);
ftSum.updatesum(map.get(curv), curx);
}
pw.println(ans);
pw.flush();
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] takearr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] takearrl(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public Integer[] takearrobj(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] takearrlobj(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
public class C1311F_1 {
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
var n = scanner.nextInt();
var x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = scanner.nextInt();
// x[i] = (int) (Math.random() * 2e8 - 1e8);
// x[i] = (int) (Math.random() * n / 2 + n / 2);
}
var v = new int[n];
for (int i = 0; i < n; i++) {
v[i] = scanner.nextInt();
// v[i] = (int) (Math.random() * 2e8 - 1e8);
// v[i] = (int) (Math.random() * 2 * n - n);
}
writer.println(solve(n, x, v));
scanner.close();
writer.flush();
writer.close();
}
static final int MIN_V = (int) -1e8;
static final int MAX_V = (int) 1e8;
private static long solve(int n, int[] x, int[] v) {
var debug = false; //n == 200000;
var orderX = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
orderX.add(i);
}
var t = System.nanoTime();
orderX.sort(Comparator.comparingInt(o -> x[o]));
if (debug) {
System.out.println("sort finished: " + (System.nanoTime() - t) / 1e9);
}
t = System.nanoTime();
var ans = 0L;
var toLeft = new SegTree(v);
var toRight = new SegTree(v);
for (int i = 0; i < n; i++) {
var thisX = x[orderX.get(i)];
var thisV = v[orderX.get(i)];
if (thisV >= 0) {
var left = toLeft.acc(MIN_V, 0);
ans += left[1] * thisX - left[0];
var right = toRight.acc(0, thisV);
ans += right[1] * thisX - right[0];
toRight.add(thisV, thisX);
} else {
var left = toLeft.acc(MIN_V, thisV);
ans += left[1] * thisX - left[0];
toLeft.add(thisV, thisX);
}
}
if (debug) {
System.out.println("finish acc: " + (System.nanoTime() - t) / 1e9);
}
return ans;
}
static class SegTree {
final List<Node> nodes = new ArrayList<>();
/**
* ζζζζηkeyοΌιε’γ
*/
final int[] keys;
SegTree(int[] keys) {
this.keys = distinctAndAsc(keys);
nodes.add(new Node(0, this.keys.length - 1));
}
static int[] distinctAndAsc(int[] keys) {
var distinct = new HashSet<Integer>();
for (int key : keys) {
distinct.add(key);
}
var asc = new ArrayList<>(distinct);
asc.sort(Integer::compareTo);
return asc.stream().mapToInt(i -> i).toArray();
}
void add(int key, int value) {
add(0, key, value);
}
private void add(int index, int key, int value) {
if (index < 0) {
return;
}
var node = nodes.get(index);
// debug("node %d: (low=%d,highEx=%d)", index, node.low, node.high);
if (key < keys[node.low] || keys[node.high] < key) {
return;
}
node.acc[0] += value;
node.acc[1]++;
if (node.isLeaf()) {
return;
}
if (node.left < 0) {
nodes.add(new Node(node.low, node.mid));
node.left = nodes.size() - 1;
}
add(node.left, key, value);
if (node.right < 0) {
nodes.add(new Node(node.mid + 1, node.high));
node.right = nodes.size() - 1;
}
add(node.right, key, value);
}
long[] acc(int lowKey, int highKey) {
return acc(0, lowKey, highKey);
}
static final long[] EMPTY = new long[]{0, 0};
private long[] acc(int index, int lowKey, int highKey) {
if (lowKey > highKey || index < 0) {
return EMPTY;
}
var node = nodes.get(index);
if (highKey < keys[node.low] || keys[node.high] < lowKey) {
return EMPTY;
}
if (lowKey <= keys[node.low] && keys[node.high] <= highKey) {
return node.acc;
}
var left = acc(node.left, lowKey, highKey);
var right = acc(node.right, lowKey, highKey);
return new long[]{left[0] + right[0], left[1] + right[1]};
}
static class Node {
final int low;
final int high;
final int mid;
int left = -1;
int right = -1;
long[] acc = new long[]{0, 0};
Node(int low, int high) {
this.low = low;
this.high = high;
this.mid = Math.floorDiv(low + high, 2);
}
public boolean isLeaf() {
return low >= high;
}
}
}
static void debug(String fmt, Object... args) {
System.out.println(String.format(fmt, args));
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(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;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
|
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 query(int a, vector<long long>& ft) {
long long res = 0;
for (; ~a; a = (a & (a + 1)) - 1) {
res += ft[a];
}
return res;
}
void update(int a, int val, vector<long long>& ft) {
for (; a < ft.size(); a = a | (a + 1)) {
ft[a] += val;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<pair<int, int>> pt(n);
map<int, int> idx;
for (auto& i : pt) {
cin >> i.first;
}
for (auto& i : pt) {
cin >> i.second;
idx[i.second] = 0;
}
sort(pt.begin(), pt.end());
int sz = 0;
for (auto& i : idx) {
i.second = sz++;
}
long long ans = 0;
vector<long long> ct(sz), coord(sz);
for (auto i : pt) {
int tmp = idx[i.second];
ans += i.first * query(tmp, ct) - query(tmp, coord);
update(tmp, 1, ct);
update(tmp, i.first, coord);
}
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;
pair<long long, long long> st[800005];
void update(long long node, long long beg, long long end, long long pos,
long long dist) {
if (beg == end) {
st[node].first += 1;
st[node].second += dist;
return;
}
long long mid = beg + (end - beg) / 2;
if (pos <= mid)
update(2 * node + 1, beg, mid, pos, dist);
else
update(2 * node + 2, mid + 1, end, pos, dist);
st[node] = {st[2 * node + 1].first + st[2 * node + 2].first,
st[2 * node + 1].second + st[2 * node + 2].second};
}
pair<long long, long long> query(long long node, long long beg, long long end,
long long ql, long long qr) {
if (beg > end || beg > qr || end < ql) return {0, 0};
if (beg >= ql && end <= qr) return st[node];
long long mid = beg + (end - beg) / 2;
pair<long long, long long> a = query(2 * node + 1, beg, mid, ql, qr);
pair<long long, long long> b = query(2 * node + 2, mid + 1, end, ql, qr);
return {a.first + b.first, a.second + b.second};
}
int main() {
long long n;
cin >> n;
vector<pair<long long, long long> > v(n);
vector<long long> vel(n);
for (long long i = 0; i < n; i++) cin >> v[i].first;
map<long long, long long> velocity_idx;
for (long long i = 0; i < n; i++) {
cin >> v[i].second;
velocity_idx[v[i].second] = 1;
}
sort(v.begin(), v.end());
long long cnt = 0;
for (auto it : velocity_idx) velocity_idx[it.first] = cnt++;
memset(st, 0, sizeof(st));
long long sz = (long long)velocity_idx.size() - 1;
long long ans = 0;
for (long long i = 0; i < n; i++) {
pair<long long, long long> p =
query(0, 0, sz, 0, velocity_idx[v[i].second]);
ans += (v[i].first * p.first - p.second);
update(0, 0, sz, velocity_idx[v[i].second], v[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;
pair<long long, long long> ara[200005];
map<long long, long long> mark;
long long seg[4 * 300005], seg2[4 * 300005];
long long query(long long qlo, long long qhi, long long lo, long long hi,
long long pos) {
if (qlo > hi || qhi < lo || qlo > qhi) return 0;
if (qlo <= lo && qhi >= hi) return seg[pos];
long long mid = (lo + hi) / 2;
return query(qlo, qhi, lo, mid, 2 * pos) +
query(qlo, qhi, mid + 1, hi, 2 * pos + 1);
}
void update(long long i, long long val, long long lo, long long hi,
long long pos) {
if (lo > i || hi < i) return;
if (lo == i && i == hi) {
seg[pos] += val;
return;
}
long long mid = (lo + hi) / 2;
update(i, val, lo, mid, 2 * pos);
update(i, val, mid + 1, hi, 2 * pos + 1);
seg[pos] = seg[2 * pos] + seg[2 * pos + 1];
}
long long query2(long long qlo, long long qhi, long long lo, long long hi,
long long pos) {
if (qlo > hi || qhi < lo || qlo > qhi) return 0;
if (qlo <= lo && qhi >= hi) return seg2[pos];
long long mid = (lo + hi) / 2;
return query2(qlo, qhi, lo, mid, 2 * pos) +
query2(qlo, qhi, mid + 1, hi, 2 * pos + 1);
}
void update2(long long i, long long val, long long lo, long long hi,
long long pos) {
if (lo > i || hi < i) return;
if (lo == i && i == hi) {
seg2[pos] += val;
return;
}
long long mid = (lo + hi) / 2;
update2(i, val, lo, mid, 2 * pos);
update2(i, val, mid + 1, hi, 2 * pos + 1);
seg2[pos] = seg2[2 * pos] + seg2[2 * pos + 1];
}
vector<long long> vec;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n;
cin >> n;
long long i, j, k;
for (i = 1; i <= n; i++) {
cin >> ara[i].second;
vec.push_back(ara[i].second);
}
sort(vec.begin(), vec.end());
for (i = 0; i < n; i++) {
mark[vec[i]] = i + 1;
}
for (i = 1; i <= n; i++) {
cin >> ara[i].first;
}
sort(ara + 1, ara + n + 1);
long long fin = 0;
for (i = n; i >= 1; i--) {
long long cur = ara[i].second;
long long tmp = mark[cur];
long long ans = query(tmp + 1, n, 1, n, 1);
fin += ans;
ans = query2(tmp + 1, n, 1, n, 1);
fin -= (ans * cur);
update(tmp, cur, 1, n, 1);
update2(tmp, 1, 1, n, 1);
}
cout << fin << 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 MOD = 1000000007;
const int INF = 1000000007;
const int MAXN = (int)2e5 + 1;
void setIO(string name) {
ios_base::sync_with_stdio(0);
cin.tie(0);
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
pair<pair<long long, long long>, int> xv[MAXN];
long long n, BIT[MAXN], BIT2[MAXN];
void update(int x, long long val) {
for (; x <= n; x += x & -x) {
BIT[x] += val;
BIT2[x]++;
}
}
pair<long long, long long> query(int x) {
long long sum = 0;
long long num = 0;
for (; x > 0; x -= x & -x) {
sum += BIT[x];
num += BIT2[x];
}
return {sum, num};
}
bool comp(pair<pair<long long, long long>, int> a,
pair<pair<long long, long long>, int> b) {
if (a.first.second == b.first.second) return a.first.first < b.first.first;
return a.first.second < b.first.second;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> xv[i].first.first;
}
for (int i = 0; i < n; i++) {
cin >> xv[i].first.second;
}
sort(xv, xv + n);
for (int i = 0; i < n; i++) {
xv[i].second = i + 1;
}
long long ans = 0;
sort(xv, xv + n, comp);
for (int i = 0; i < n; i++) {
pair<long long, long long> res = query(xv[i].second);
ans += (res.second * xv[i].first.first - res.first);
update(xv[i].second, xv[i].first.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
|
python3
|
import bisect
class Bit :
def __init__(self, n) :
self.bit = [0 for i in range(0, n)]
def add(self, pos, x) :
while pos < len(self.bit) :
self.bit[pos] += x
pos = pos | (pos + 1)
def query(self, pos) :
res = 0
while pos > 0 :
res += self.bit[pos - 1];
pos = pos & (pos - 1)
return res
n = int(input())
x = [int(i) for i in input().split()]
v = [int(i) for i in input().split()]
r = [i for i in range(n)]
r.sort(key = lambda i : x[i])
unique = sorted(list(set(v)))
tree1, tree2 = Bit(len(unique)), Bit(len(unique))
ans = 0
for i in r :
ii = bisect.bisect_left(unique, v[i])
count = tree1.query(ii + 1)
dsum = tree2.query(ii + 1)
ans += count * x[i] - dsum
tree1.add(ii, 1)
tree2.add(ii, x[i])
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 cnt[400000], cnt1[400000], a[400000], b[400000], number[800000];
map<int, int> mp;
vector<pair<int, int> > v;
int q(int ind) {
int sum = 0;
while (ind > 0) {
sum += number[ind];
ind -= ind & (-ind);
}
return sum;
}
void u(int ind, int n) {
int sum = 0;
while (ind <= n) {
number[ind]++;
ind += ind & (-ind);
}
}
int main() {
{
ios_base::sync_with_stdio(false);
cin.tie(0);
};
int i, j, n, m, k, l = 0, h, t;
long long ans = 0;
cin >> n;
for (i = 1; i <= n; i++) cin >> a[i];
for (i = 1; i <= n; i++) {
cin >> b[i];
v.push_back({a[i], b[i]});
}
sort(b + 1, b + n + 1);
j = 1;
for (i = 1; i <= n; i++) {
if (!mp[b[i]]) mp[b[i]] = j++;
cnt[mp[b[i]]]++;
}
for (i = 1; i < j; i++) b[i] = b[i - 1] + cnt[i - 1];
sort(v.begin(), v.end());
for (i = 0; i < n; i++) {
k = v[i].first;
l = v[i].second;
l = mp[l];
u(l, j - 1);
cnt1[l]++;
m = q(l);
h = n - i - 1 - (cnt[l] + b[l] - m) + cnt[l] - cnt1[l];
ans += (long long)k * (m - 1 - h);
}
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;
long long query(vector<long long>& ft, int pos) {
long long ans = 0;
while (pos > 0) {
ans += ft[pos - 1];
pos -= (pos & (-pos));
}
return ans;
}
void update(vector<long long>& ft, int pos, long long val, int& ceil) {
while (pos <= ceil) {
ft[pos - 1] += val;
pos += (pos & (-pos));
}
}
int main() {
int n;
cin >> n;
vector<pair<int, int>> p(n);
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> p[i].first;
for (int i = 0; i < n; i++) {
cin >> p[i].second;
v[i] = p[i].second;
}
sort(p.begin(), p.end());
sort(v.begin(), v.end());
v.resize(unique(v.begin(), v.end()) - v.begin());
int ceil = v.size();
vector<long long> ftx(ceil), ftc(ceil);
long long ans = 0;
for (int i = 0; i < n; i++) {
int pos = lower_bound(v.begin(), v.end(), p[i].second) - v.begin();
ans += query(ftc, pos + 1) * (1ll * p[i].first) - query(ftx, pos + 1);
update(ftc, pos + 1, 1, ceil);
update(ftx, pos + 1, p[i].first, ceil);
}
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
|
import heapq
import sys
input = sys.stdin.readline
def make_tree(n):
tree = [0] * (n + 1)
return tree
def get_sum(i, tree):
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
def add(i, x, tree):
while i <= n:
tree[i] += x
i += i & -i
n = int(input())
x = list(map(int, input().split()))
v = list(map(int, input().split()))
u = list(set(v))
u.sort(reverse = True)
m = len(u)
d = dict()
for i in range(m):
d[u[i]] = i + 2
tree = make_tree(n + 5)
cnt = make_tree(n + 5)
ans = 0
h = []
for i in range(n):
heapq.heappush(h, (x[i], i))
sx = []
while h:
xi, i = heapq.heappop(h)
sx.append(xi)
vi = v[i]
di = d[vi]
ans -= get_sum(di - 1, cnt) * xi - get_sum(di - 1, tree)
add(di, xi, tree)
add(di, 1, cnt)
for i in range(n - 1):
ans += (i + 1) * (n - i - 1) * (sx[i + 1] - sx[i])
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
template <class T, class U>
bool ckmin(T& a, U& b) {
return b < a ? a = b, 1 : 0;
}
template <class T, class U>
bool ckmax(T& a, U& b) {
return a < b ? a = b, 1 : 0;
}
int pct(int x) { return __builtin_popcount(x); }
long long FIRSTTRUE(function<bool(long long)> first, long long lower_bound,
long long rb) {
while (lower_bound < rb) {
long long mb = (lower_bound + rb) / 2;
first(mb) ? rb = mb : lower_bound = mb + 1;
}
return lower_bound;
}
long long LASTTRUE(function<bool(long long)> first, long long lower_bound,
long long rb) {
while (lower_bound < rb) {
long long mb = (lower_bound + rb + 1) / 2;
first(mb) ? lower_bound = mb : rb = mb - 1;
}
return lower_bound;
}
namespace input {
template <class T>
void re(complex<T>& x);
template <class T1, class T2>
void re(pair<T1, T2>& p);
template <class T>
void re(vector<T>& a);
template <class T, size_t SZ>
void re(array<T, SZ>& a);
template <class T>
void re(T& x) {
cin >> x;
}
void re(double& x) {
string t;
re(t);
x = stod(t);
}
void re(long double& x) {
string t;
re(t);
x = stold(t);
}
template <class T, class... Ts>
void re(T& t, Ts&... ts) {
re(t);
re(ts...);
}
template <class T>
void re(complex<T>& x) {
T a, b;
re(a, b);
x = {a, b};
}
template <class T1, class T2>
void re(pair<T1, T2>& p) {
re(p.first, p.second);
}
template <class T>
void re(vector<T>& a) {
for (int i = (0); i < ((int)a.size()); ++i) re(a[i]);
}
template <class T, size_t SZ>
void re(array<T, SZ>& a) {
for (int i = (0); i < (SZ); ++i) re(a[i]);
}
} // namespace input
using namespace input;
namespace output {
void pr(int x) { cout << x; }
void pr(long x) { cout << x; }
void pr(long long x) { cout << x; }
void pr(unsigned x) { cout << x; }
void pr(unsigned long x) { cout << x; }
void pr(unsigned long long x) { cout << x; }
void pr(float x) { cout << x; }
void pr(double x) { cout << x; }
void pr(long double x) { cout << x; }
void pr(char x) { cout << x; }
void pr(const char* x) { cout << x; }
void pr(const string& x) { cout << x; }
void pr(bool x) { pr(x ? "true" : "false"); }
template <class T>
void pr(const complex<T>& x) {
cout << x;
}
template <class T1, class T2>
void pr(const pair<T1, T2>& x);
template <class T>
void pr(const T& x);
template <class T, class... Ts>
void pr(const T& t, const Ts&... ts) {
pr(t);
pr(ts...);
}
template <class T1, class T2>
void pr(const pair<T1, T2>& x) {
pr("{", x.first, ", ", x.second, "}");
}
template <class T>
void pr(const T& x) {
pr("{");
bool fst = 1;
for (const auto& a : x) pr(!fst ? ", " : "", a), fst = 0;
pr("}");
}
void ps() { pr("\n"); }
template <class T, class... Ts>
void ps(const T& t, const Ts&... ts) {
pr(t);
if (sizeof...(ts)) pr(" ");
ps(ts...);
}
void pc() { pr("]\n"); }
template <class T, class... Ts>
void pc(const T& t, const Ts&... ts) {
pr(t);
if (sizeof...(ts)) pr(", ");
pc(ts...);
}
} // namespace output
using namespace output;
namespace io {
void setIn(string second) { freopen(second.c_str(), "r", stdin); }
void setOut(string second) { freopen(second.c_str(), "w", stdout); }
void setIO(string second = "") {
ios_base::sync_with_stdio(0);
cin.tie(0);
if ((int)second.size()) {
setIn(second + ".in"), setOut(second + ".out");
}
}
} // namespace io
using namespace io;
const int MOD = 1000000007;
struct mi {
typedef decay<decltype(MOD)>::type T;
T v;
explicit operator T() const { return v; }
mi() { v = 0; }
mi(long long _v) {
v = (-MOD < _v && _v < MOD) ? _v : _v % MOD;
if (v < 0) v += MOD;
}
friend bool operator==(const mi& a, const mi& b) { return a.v == b.v; }
friend bool operator!=(const mi& a, const mi& b) { return !(a == b); }
friend bool operator<(const mi& a, const mi& b) { return a.v < b.v; }
friend void re(mi& a) {
long long x;
re(x);
a = mi(x);
}
friend void pr(const mi& a) { pr(a.v); }
friend ostream& operator<<(ostream& os, const mi& a) { return os << a.v; }
mi& operator+=(const mi& m) {
if ((v += m.v) >= MOD) {
v -= MOD;
}
return *this;
}
mi& operator-=(const mi& m) {
if ((v -= m.v) < 0) {
v += MOD;
}
return *this;
}
mi& operator*=(const mi& m) {
v = (long long)v * m.v % MOD;
return *this;
}
mi& operator/=(const mi& m) { return (*this) *= inv(m); }
friend mi pow(mi a, long long p) {
mi ans = 1;
assert(p >= 0);
for (; p; p /= 2, a *= a)
if (p & 1) ans *= a;
return ans;
}
friend mi inv(const mi& a) {
assert(a.v != 0);
return pow(a, MOD - 2);
}
mi operator-() const { return mi(-v); }
mi& operator++() { return *this += 1; }
mi& operator--() { return *this -= 1; }
friend mi operator+(mi a, const mi& b) { return a += b; }
friend mi operator-(mi a, const mi& b) { return a -= b; }
friend mi operator*(mi a, const mi& b) { return a *= b; }
friend mi operator/(mi a, const mi& b) { return a /= b; }
};
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());
const int MAX = 200001;
template <class T>
struct BIT {
T bit[MAX];
long long SZ;
BIT(T n) { SZ = n; }
void update(T pos, T val) {
while (pos <= SZ) {
bit[pos] += val;
pos += pos & -pos;
}
}
T sum(long long ind) {
T res = 0;
while (ind > 0) {
res += bit[ind];
ind -= ind & -ind;
}
return res;
}
T query(T l, T r) { return sum(r) - sum(l - 1); }
};
struct node {
long long loc, fast, ind;
node(long long l, long long first, long long i) {
loc = l, fast = first, ind = i;
}
};
bool cmp(node a, node b) { return a.loc < b.loc; }
int main() {
long long n;
cin >> n;
vector<long long> pos(n + 1, 0), speed(n + 1, 0);
for (int i = (1); i < (n + 1); ++i) {
cin >> pos[i];
}
for (int i = (1); i < (n + 1); ++i) {
cin >> speed[i];
}
vector<node> a(n + 1, {0, 0, 0});
for (int i = (1); i < (n + 1); ++i) {
a[i] = {pos[i], speed[i], (long long)i};
}
long long curid = 1;
vector<long long> s1 = speed;
sort(s1.begin() + 1, s1.end());
map<long long, long long> track;
for (int i = 1; i <= n; i++) {
track[s1[i]] = curid++;
}
for (int i = (1); i < (n + 1); ++i) {
a[i].ind = track[a[i].fast];
}
BIT<long long> inv(n), inv1(n);
sort(1 + a.begin(), a.end(), cmp);
long long ans = 0;
for (int i = n; i >= 1; i--) {
auto pos1 = lower_bound(s1.begin() + 1, s1.end(), a[i].fast) - s1.begin();
long long qry = inv.query(pos1, n);
long long qry1 = inv1.query(pos1, n);
ans += (qry - (qry1 * a[i].loc));
inv.update(a[i].ind, a[i].loc);
inv1.update(a[i].ind, 1);
}
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e5 + 1000;
pair<long long, long long> p[maxn];
vector<long long> v;
int getpos(long long V) {
return lower_bound(v.begin(), v.end(), V) - v.begin() + 1;
}
long long C1[2][maxn];
long long C2[2][maxn];
void add(int x, long long K, long long C[][maxn]) {
while (x < maxn) {
C[0][x] += 1;
C[1][x] += K;
x += (x) & (-x);
}
}
pair<long long, long long> getsum(int x, long long C[][maxn]) {
long long sum = 0;
int num = 0;
while (x > 0) {
num += C[0][x];
sum += C[1][x];
x -= (x) & (-x);
}
return pair<long long, long long>(num, sum);
}
int main() {
ios::sync_with_stdio(false);
int N;
cin >> N;
for (int i = 1; i <= N; i++) cin >> p[i].first;
for (int i = 1; i <= N; i++)
cin >> p[i].second, v.push_back(abs(p[i].second));
sort(p + 1, p + 1 + N);
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
long long ans = 0;
long long cnt2 = 0;
long long cnts2 = 0;
for (int i = 1; i <= N; i++) {
if (p[i].second >= 0) {
pair<long long, long long> s = getsum(getpos(p[i].second), C1);
ans += p[i].first * s.first - s.second;
add(getpos(p[i].second), p[i].first, C1);
ans += p[i].first * cnt2 - cnts2;
} else {
pair<long long, long long> s = getsum(getpos(-p[i].second), C2);
ans += -p[i].first * s.first - s.second;
add(getpos(-p[i].second), p[i].first, C2);
cnt2 += 1;
cnts2 += 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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
template <class Ch, class Tr, class Container>
basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os,
Container const& x) {
os << "{ ";
for (auto& y : x) os << y << " ";
return os << "}";
}
template <class X, class Y>
ostream& operator<<(ostream& os, pair<X, Y> const& p) {
return os << "[ " << p.first << ", " << p.second << "]";
}
typedef struct {
long long pos, v;
} Point;
long long P[200005], V[200005], sum = 0, maxNeg = 0;
long long l = 0, r = 200000000;
int n;
vector<Point> Pos, Neg;
bool sort_vel(Point a, Point b) {
if (a.v == b.v) return a.pos > b.pos;
return a.v > b.v;
}
bool sort_pos(Point a, Point b) { return a.pos < b.pos; }
long long ft[200005];
void upd(int i0, long long v) {
for (int i = i0 + 1; i <= 200005; i += i & -i) ft[i] += v;
}
long long get(int i0) {
long long r = 0;
for (int i = i0; i; i -= i & -i) r += ft[i];
return r;
}
int get_sum(int i0, int i1) { return get(i1) - get(i0); }
void solve(vector<Point>& v) {
int sz = v.size();
for (int i = 0; i < (200005); i++) ft[i] = 0;
sort((v.begin()), (v.end()), sort_pos);
for (int i = 0; i < (sz); i++) upd(i, r - v[i].pos);
map<long long, long long> DondeEsta;
for (int i = 0; i < (sz); i++) DondeEsta[v[i].pos] = i;
sort((v.begin()), (v.end()), sort_vel);
set<long long> usados;
for (auto x : v) {
int i = DondeEsta[x.pos];
int dif = 0;
dif = distance(usados.begin(),
upper_bound((usados.begin()), (usados.end()), x.pos));
sum += get_sum(0, i) - ((r - x.pos) * (i - dif));
upd(i, -1 * get_sum(i, i + 1));
usados.insert(x.pos);
}
}
int main() {
cin >> n;
for (int i = 0; i < (n); i++) cin >> P[i];
for (int i = 0; i < (n); i++) {
cin >> V[i];
if (V[i] >= 0)
Pos.push_back({P[i], V[i]});
else {
maxNeg = max(maxNeg, P[i]);
Neg.push_back({P[i], -1 * V[i]});
Pos.push_back({P[i], -1});
}
}
for (auto& x : Neg) x.pos = maxNeg + abs(x.pos - maxNeg);
solve(Pos);
solve(Neg);
cout << sum << 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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
pair<int, int> p[N];
long long cnt[N], val[N];
void update(int a, int b, int l, int r, int rt, int v) {
if (a <= l && b >= r) {
val[rt] += v, cnt[rt]++;
return;
}
int mid = l + r >> 1;
if (a <= mid) update(a, b, l, mid, rt << 1, v);
if (b > mid) update(a, b, mid + 1, r, rt << 1 | 1, v);
cnt[rt] = cnt[rt << 1] + cnt[rt << 1 | 1];
val[rt] = val[rt << 1] + val[rt << 1 | 1];
}
pair<long long, int> query(int a, int b, int l, int r, int rt) {
if (a <= l && b >= r) {
return {val[rt], cnt[rt]};
}
int mid = l + r >> 1;
pair<int, int> ans = {0, 0}, t = {0, 0}, t2 = {0, 0};
if (a <= mid) t = query(a, b, l, mid, rt << 1);
if (b > mid) t2 = query(a, b, mid + 1, r, rt << 1 | 1);
ans.first = t.first + t2.first;
ans.second = t.second + t2.second;
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i = 0; i < n; ++i) cin >> p[i].first;
for (int i = 0; i < n; ++i) cin >> p[i].second;
sort(p, p + n);
vector<int> a(n);
for (int i = 0; i < n; ++i) a[i] = p[i].second;
sort(a.begin(), a.end());
a.resize(unique(a.begin(), a.end()) - a.begin());
for (int i = 0; i < n; ++i) {
p[i].second = lower_bound(a.begin(), a.end(), p[i].second) - a.begin() + 1;
}
long long ans = 0;
for (int i = n - 1; ~i; --i) {
update(p[i].second, p[i].second, 1, 200000, 1, p[i].first);
auto t = query(p[i].second, 200000, 1, 200000, 1);
ans += t.first - t.second * p[i].first;
}
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int n;
struct dd {
int gt;
int x;
int v;
};
vector<dd> a;
struct Data {
long long sum;
int sl;
Data operator+(const Data& a) {
sum = sum + a.sum;
sl = sl + a.sl;
return *this;
}
};
Data it[200009 * 8];
Data ans;
long long res;
void update(int i, int l, int r, int pos, int data) {
if (l > pos || r < pos) return;
if (l == r) {
it[i].sum = data;
it[i].sl = 1;
return;
}
int mid = (l + r) / 2;
update(i * 2, l, mid, pos, data);
update(i * 2 + 1, mid + 1, r, pos, data);
it[i] = it[i * 2] + it[i * 2 + 1];
}
void find(int i, int l, int r, int u, int v) {
if (l > r) return;
if (l > v || r < u) return;
if (u <= l && r <= v) {
ans = ans + it[i];
return;
}
int mid = (l + r) / 2;
find(i * 2, l, mid, u, v);
find(i * 2 + 1, mid + 1, r, u, v);
}
bool cmp(const dd& a, const dd& b) { return a.v < b.v; }
bool cmp1(const dd& a, const dd& b) { return a.x < b.x; }
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
dd tmp;
cin >> tmp.x;
a.push_back(tmp);
}
for (int i = 0; i < n; i++) {
cin >> a[i].v;
}
sort(a.begin(), a.end(), cmp1);
for (int i = 0; i < n; i++) {
a[i].gt = i + 1;
}
sort(a.begin(), a.end(), cmp);
update(1, 1, n, a[n - 1].gt, a[n - 1].x);
for (int i = n - 2; i >= 0; i--) {
long long tmp = a[i].x;
ans.sl = 0;
ans.sum = 0;
find(1, 1, n, a[i].gt + 1, n);
res = res + ans.sum - (tmp * ans.sl);
update(1, 1, n, a[i].gt, a[i].x);
}
cout << res << 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": []
}
|
IN-CORRECT
|
java
|
import java.util.Scanner;
public class Moving_Points {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int[] x = new int[n];
for (int i = 0; i < n; i++)
x[i] = reader.nextInt();
int[] v = new int[n];
for (int i = 0; i < n; i++)
v[i] = reader.nextInt();
reader.close();
int sum = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (v[i] * v[j] < 0 || v[i] == v[j] || (v[i] * v[j] > 0 && (x[i] < x[j] && v[i] < v[j]))) {
sum += Math.abs(x[i] - x[j]);
} else if (v[i] * v[j] == 0) {
if ((v[i] == 0 && ((x[j] > x[i] && v[j] > 0) || (x[j] < x[i] && v[j] < 0))
|| (v[j] == 0 && ((x[i] > x[j] && v[i] > 0) || (x[i] < x[j] && v[i] < 0))))
)
sum += Math.abs(x[i] - x[j]);
}
}
}
System.out.print(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": []
}
|
IN-CORRECT
|
java
|
import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class template {
final static int MOD = 1000000007;
final static int intMax = 1000000000;
final static int intMin = -1000000000;
final static int[] DX = { 0, 0, -1, 1 };
final static int[] DY = { -1, 1, 0, 0 };
static int T;
static 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[360]; // line length
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();
}
}
public static void main(String[] args) throws Exception {
Reader in = new Reader();
int n = in.nextInt();
int[] x = new int[n];
int[] v = new int[n];
for(int i = 0; i < n; ++i) {
x[i] = in.nextInt();
}
for(int i = 0; i < n; ++i) {
v[i] = in.nextInt();
}
p[] points = new p[n];
for(int i = 0; i < n; ++i) {
points[i] = new p(x[i], v[i]);
}
Arrays.sort(points, (a, b) -> a.x - b.x);
for(int i = 0; i < n; ++i) {
points[i].orig = i + 1;
}
long [] dists = new long[n];
long count = 1L;
for(int i = n - 2; i >= 0; --i) {
dists[i] = dists[i + 1] + (count++) * ((long) (points[i + 1].x - points[i].x));
}
if(n == 161) {
for(int i = 0; i < n; ++i) {
System.out.println(dists[i]);
}
}
long tot = 0;
for(int i = 0; i < n; ++i) {
tot += dists[i];
}
BinaryIndexedTree num = new BinaryIndexedTree(n);
BinaryIndexedTree inds = new BinaryIndexedTree(n);
Arrays.sort(points, (a, b) -> a.v == b.v ? b.orig - a.orig : b.v - a.v);
for(int i = 0; i < n; ++i) {
long amt = num.query(points[i].orig);
long totinds = inds.query(points[i].orig);
tot -= amt * points[i].x - totinds;
num.update(points[i].orig, 1);
inds.update(points[i].orig, points[i].orig);
}
System.out.println(tot);
in.close();
}
static class p{
int x, v, orig;
p(int xi, int vi){
x = xi; v = vi;
}
}
static class BinaryIndexedTree {
public long[] tree;
public BinaryIndexedTree(int n) {
tree = new long[n+5];
}
public void update(int index, int val) {
index++;
while(index < tree.length) {
tree[index] += (long) val;
index += index & -index;
}
}
//sum from 0 to index
public long query(int index) {
long ret = 0;
index++;
while(index > 0) {
ret += tree[index];
index -= index & -index;
}
return ret;
}
//sum from a to b
public long query(int a, int b) {
return query(b)-query(a-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": []
}
|
IN-CORRECT
|
java
|
/* / οΎοΎβ β β β β β β β β β β β γ
/ )\β β β β β β β β β β β β Y
(β β | ( Ν‘Β° ΝΚ Ν‘Β°οΌβ β(β γ
(β οΎβ Y βγ½-γ __οΌ
| _β qγ| γq |/
(β γΌ '_δΊΊ`γΌ οΎ
β |\ οΏ£ _δΊΊ'彑οΎ
β )\β β qβ β /
β β (\β #β /
β /β β β /α½£====================D-
/β β β /β \ \β β \
( (β )β β β β ) ).β )
(β β )β β β β β ( | /
|β /β β β β β β | /
[_] β β β β β [___] */
// Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else 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;
}
}
static long MOD=1000000000+7;
//Euclidean Algorithm
static long gcd(long A,long B){
return (B==0)?A:gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//Modular Inverse
static long inverse(long x) {
return fastExpo(x,MOD-2);
}
//Prime Number Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Reverse an array
static void reverse(int arr[],int l,int r){
while(l<r) {
int tmp=arr[l];
arr[l++]=arr[r];
arr[r--]=tmp;
}
}
//Print array
static void print1d(int arr[]) {
out.println(Arrays.toString(arr));
}
static void print2d(int arr[][]) {
for(int a[]: arr) out.println(Arrays.toString(a));
}
// Pair
static class pair{
int x,y;
pair(int a,int b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Main function(The main code starts from here)
static int N=200000;
static pair bit[]=new pair[N+1];
static void add(int idx,int val) {
while(idx<=N) {
bit[idx].x++;
bit[idx].y+=val;
idx+=idx&-idx;
}
}
static pair sum(int idx) {
pair res=new pair(0,0);
while(idx>0) {
res.x+=bit[idx].x;
res.y+=bit[idx].y;
idx-=idx&-idx;
}
return res;
}
public static void main (String[] args) throws java.lang.Exception {
int test;
test=1;
//test=sc.nextInt();
while(test-->0){
for(int i=0;i<=N;i++) bit[i]=new pair(0,0);
int n=sc.nextInt();
pair a[]=new pair[n];
for(int i=0;i<n;i++) a[i]=new pair(sc.nextInt(),-1);
HashMap<Integer,Integer> map=new HashMap<>();
TreeSet<Integer> set=new TreeSet<>();
for(int i=0;i<n;i++) {
a[i].y=sc.nextInt();
set.add(a[i].y);
}
Arrays.parallelSort(a,(p1,p2)->p1.x-p2.x);
int idx=1;
for(Integer x: set) map.put(x,idx++);
long ans=0;
for(int i=n-1;i>=0;i--) {
idx=map.get(a[i].y);
int val=a[i].x;
pair r=sum(N),l=sum(idx-1);
long x=r.y-l.y,y=r.x-l.x;
ans+=x-val*y;
add(idx,val);
}
out.println(ans);
}
out.flush();
out.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": []
}
|
IN-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(deque)
for i in range(n):
d1[l[i]].append(s[i])
ind=[i for i in range(n)]
ind=sort_list(ind,s)
s.sort()
d=defaultdict(deque)
for i in range(n):
d[s[i]].append(ind[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]][0]
d1[l[i]].popleft()
pos=d[sp][0]
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)
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline T read(T &x) {
char c = getchar();
bool f = 0;
x = 0;
while (!isdigit(c)) f |= c == '-', c = getchar();
while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
if (f) x = -x;
return x;
}
template <typename T, typename... Args>
inline void read(T &x, Args &...args) {
read(x);
read(args...);
}
template <typename T>
inline void write(T x) {
if (x < 0)
putchar('-'), write(-x);
else {
if (x > 9) write(x / 10);
putchar('0' + x % 10);
}
}
int N;
struct Z {
int x, v, idx;
} A[200005];
long long bit[200005];
int cbit[200005];
void add(int n, int v) {
for (; n <= N; n += n & -n) bit[n] += v, cbit[n]++;
}
void get(int s, int e, long long &sum, int &cnt) {
sum = cnt = 0;
for (; e; e ^= e & -e) sum += bit[e], cnt += cbit[e];
for (s--; s; s ^= s & -s) sum -= bit[s], cnt -= cbit[s];
}
int main() {
read(N);
for (int i = 1; i <= N; i++) read(A[i].x);
for (int i = 1; i <= N; i++) read(A[i].v);
sort(A + 1, A + N + 1, [](const Z &a, const Z &b) { return a.x < b.x; });
for (int i = 1; i <= N; i++) A[i].idx = i;
sort(A + 1, A + N + 1, [](const Z &a, const Z &b) { return a.v < b.v; });
long long ans = 0;
for (int i = N; i; i--) {
add(A[i].idx, A[i].x);
long long sum = 0;
int cnt = 0;
get(A[i].idx + 1, N, sum, cnt);
ans += sum - (long long)A[i].x * cnt;
}
write(ans);
puts("");
}
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
signed main() {
ios::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n;
cin >> n;
vector<pair<long long, long long> > a(n, {0, 0});
for (long long i = 0; i < n; i++) {
long long x;
cin >> x;
a[i].first = x;
}
for (long long i = 0; i < n; i++) {
long long v;
cin >> v;
a[i].second = v;
}
sort(a.begin(), a.end());
vector<long long> x, dp(n, 0);
long long ans = 0;
for (long long i = 0; i < n; i++) {
if (i > 0) {
long long v = upper_bound(x.begin(), x.end(), a[i].second) - x.begin();
dp[i] = dp[i - 1] + (i * (a[i].first - a[i - 1].first));
ans += dp[v] + (v * (a[i].first - a[v].first));
x.push_back(a[i].second);
} else {
x.push_back(a[i].second);
}
}
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": []
}
|
IN-CORRECT
|
python3
|
numberofpoints=int(input())
initcoords=input().split(" ")
speeds=input().split(" ")
initcoords=tuple(map(int,initcoords))
speeds=tuple(map(int,speeds))
def twopoints(coords,velos):
firstv=velos[0]
secondv=velos[1]
firstc=coords[0]
secondc=coords[1]
dif=abs(firstc-secondc)
nextdif=abs((firstc+0.0001*firstv)-(secondc+0.0001*secondv))
if dif>nextdif:
return 0
else:
return dif
lis=[]
for first in range(numberofpoints):
for second in range(first+1,numberofpoints):
tup=(first,second)
lis.append(tup)
sum=0
for tuple in lis:
a=(speeds[tuple[0]],speeds[tuple[1]])
b=(initcoords[tuple[0]],initcoords[tuple[1]])
sum+=twopoints(b,a)
print(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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
template <class T>
struct fen {
vector<T> fenwick;
long long size;
fen(long long sz) {
size = sz;
fenwick.resize(size);
for (long long i = 0; i < size; i++) fenwick[i] = 0;
}
fen(vector<T> arr) {
size = arr.size();
fenwick.resize(size);
for (long long i = 0; i < size; i++) fenwick[i](0);
for (long long i = 0; i < size; i++) update(i, arr[i]);
}
void add(long long index, T add) {
for (long long k = index; k < size; k |= (~k & -~k)) {
fenwick[k] = fenwick[k] + add;
}
}
void update(long long index, T nval) {
add(index, nval - rangeQuery(index, index));
}
T query(long long to) {
if (to < 0) return 0;
T sum = 0;
for (long long curr = to + 1; curr > 0; curr ^= (curr & -curr)) {
sum = sum + fenwick[curr - 1];
}
return sum;
}
T rangeQuery(long long from, long long to) {
if (from > to) return 0;
if (!from) return query(to);
return query(to) - query(from - 1);
}
void prll() {
for (long long i = 0; i < size; i++) cout << query(i) << " ";
cout << endl;
}
};
const long long sz = 2e5 + 5;
long long n;
pair<long long, long long> xv[sz];
vector<pair<pair<long long, long long>, long long>> pos, neg;
long long ppos[sz], npos[sz];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> 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;
sort(xv, xv + n);
for (long long i = 0; i < n; i++) {
if (xv[i].second >= 0)
pos.push_back({{xv[i].second, xv[i].first}, i});
else
neg.push_back({{-xv[i].second, xv[i].first}, i});
}
sort(pos.begin(), pos.end());
sort(neg.rbegin(), neg.rend());
long long pamt = pos.size(), namt = neg.size();
for (long long i = 0; i < pamt; i++) ppos[pos[i].second] = i;
for (long long i = 0; i < namt; i++) npos[neg[i].second] = i;
fen<long long> fp(n), fpcnt(n), fn(n), fncnt(n);
long long poscnt = 0, negcnt = 0, tot = 0, negsum = 0;
for (long long i = 0; i < n; i++) {
if (xv[i].second >= 0) {
long long rk = ppos[i];
long long bamt = fpcnt.query(rk - 1);
tot += bamt * xv[i].first - fp.query(rk - 1);
fp.update(rk, xv[i].first);
fpcnt.update(rk, 1);
tot += negcnt * xv[i].first - negsum;
} else {
long long rk = npos[i];
long long bamt = fncnt.query(rk - 1);
tot += bamt * xv[i].first - fn.query(rk - 1);
fn.update(rk, xv[i].first);
fncnt.update(rk, 1);
negsum += xv[i].first;
negcnt++;
}
}
cout << tot;
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": []
}
|
IN-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.util.Comparator;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author xwchen
*/
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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] x = in.nextIntArray(n);
int[] v = in.nextIntArray(n);
v = ArrayUtils.shrink(v);
Point[] points = new Point[n];
for (int i = 0; i < n; ++i) {
points[i] = new Point(x[i], v[i]);
}
Arrays.sort(points, Comparator.comparingInt(p -> p.x));
BinaryIndexedTree Vcnt = new BinaryIndexedTree(n);
BinaryIndexedTree VXsum = new BinaryIndexedTree(n);
long res = 0;
for (int i = n - 1; i >= 0; --i) {
int X = points[i].x;
int V = points[i].v;
long cnt = Vcnt.queryRange(V + 1, n);
long sum = VXsum.queryRange(V + 1, n);
res += sum - (X - 1) * cnt;
Vcnt.update(V, 1);
VXsum.update(V, X);
}
out.println(res);
}
class Point {
int x;
int v;
public Point(int x, int v) {
this.x = x;
this.v = v;
}
}
}
static class BinaryIndexedTree {
int n;
long[] bit;
public BinaryIndexedTree(int n) {
this.n = n;
bit = new long[n + 1];
}
public void update(int i, int add) {
while (i > 0 && i < n) {
bit[i] += add;
i = i + (i & (-i));
}
}
public int sum(int i) {
int ans = 0;
while (i > 0) {
ans += bit[i];
i = i - (i & (-i));
}
return ans;
}
public int queryRange(int i, int j) {
return sum(j) - sum(i - 1);
}
}
static class ArrayUtils {
public static int[] shrink(int[] a) {
int n = a.length;
int[] ret = new int[n];
int[] b = new int[n];
TreeMap<Integer, Integer> rankOf = new TreeMap<>();
for (int i = 0; i < n; ++i) {
b[i] = a[i];
}
Arrays.sort(b);
int p = 0;
for (int i = 0; i < n; ++i) {
if (i == 0 || b[i] != b[i - 1]) {
++p;
}
rankOf.put(b[i], p);
}
for (int i = 0; i < n; ++i) {
ret[i] = rankOf.get(a[i]);
}
return ret;
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer = new StringTokenizer("");
public InputReader(InputStream inputStream) {
this.reader = new BufferedReader(
new InputStreamReader(inputStream));
}
public String next() {
while (!tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
}
}
|
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": []
}
|
IN-CORRECT
|
java
|
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class f624 implements Runnable{
public static void main(String[] args) {
try{
new Thread(null, new f624(), "process", 1<<26).start();
}
catch(Exception e){
System.out.println(e);
}
}
public void run() {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
//PrintWriter out = new PrintWriter("file.out");
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
static final int inf = Integer.MAX_VALUE;
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int N = sc.nextInt();
tup[] points = new tup[N];
long[] v = new long[N];
for(int i = 0; i < N; i++) {
points[i] = new tup();
points[i].a = sc.nextInt();
}
for(int i = 0; i < N; i++) {
points[i].b = sc.nextInt();
v[i] = points[i].b;
}
Arrays.sort(points, new tup());
//System.out.println(Arrays.toString(points));
int ID = 0;
for(int i = 0; i < N; i++) {
if(i == 0) {
points[i].b = ++ID;
continue;
}
if(v[i] == v[i-1])
points[i].b = ID;
else
points[i].b = ++ID;
}
//System.out.println(Arrays.toString(points));
Arrays.sort(points, new comp());
segt segtree = new segt(ID);
long totalSum = 0;
for(int i = 0; i < N; i++) {
tup res = segtree.querySum((int)points[i].b, ID-1);
long sum = res.a;
long nodes = res.b;
totalSum += sum - nodes * points[i].a;
//System.out.println(sum + " " + nodes + " " + totalSum);
segtree.update((int)points[i].b, (int)points[i].a);
}
out.println(totalSum);
}
static final tup ZERO = new tup(0, 0);
static class segt {
tup[] t;
int N;
public segt(int n) {
t = new tup[4*n];
for(int i = 0; i < t.length; i++) {
t[i] = new tup(0, 0);
}
N = n;
}
tup querySum(int l, int r) {
return querySum(1, 0, N-1, l, r);
}
tup querySum(int v, int tl, int tr, int l, int r) {
if (l > r)
return ZERO;
if (l == tl && r == tr)
return t[v];
int tm = (tl + tr) / 2;
tup A = querySum(v*2, tl, tm, l, Math.min(r, tm));
tup B = querySum(v*2+1, tm+1, tr, Math.max(l, tm+1), r);
return new tup(A.a + B.a, A.b + B.b);
}
void update(int pos, int new_val) {
update(1, 0, N-1, pos, new_val);
}
void update(int v, int tl, int tr, int pos, long new_val) {
if (tl == tr) {
t[v] = new tup(new_val + t[v].a, 1 + t[v].b);
} else {
int tm = (tl + tr) / 2;
if (pos <= tm)
update(v*2, tl, tm, pos, new_val);
else
update(v*2+1, tm+1, tr, pos, new_val);
t[v].a = t[v*2].a + t[v*2+1].a;
t[v].b = t[v*2].b + t[v*2+1].b;
}
}
}
}
static long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1) == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
static void sort(int[] x){
shuffle(x);
Arrays.sort(x);
}
static void sort(long[] x){
shuffle(x);
Arrays.sort(x);
}
static class comp implements Comparator<tup>{
@Override
public int compare(tup o1, tup o2) {
// TODO Auto-generated method stub
return Long.compare(o2.a, o1.a);
}
}
static class tup implements Comparable<tup>, Comparator<tup>{
long a, b;
tup(long a,long b){
this.a=a;
this.b=b;
}
public tup() {
}
@Override
public int compareTo(tup o){
return Long.compare(b,o.b);
}
@Override
public int compare(tup o1, tup o2) {
return Long.compare(o1.b, o2.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
tup other = (tup) obj;
return a==other.a && b==other.b;
}
@Override
public String toString() {
return a + " " + b;
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
inline long long read() {
char ch = getchar();
long long p = 1, data = 0;
while (ch < '0' || ch > '9') {
if (ch == '-') p = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
data = (data << 3) + (data << 1) + (ch ^ 48);
ch = getchar();
}
return p * data;
}
inline long long lowbit(long long a) { return a & (-a); }
inline long long qpow(long long a, long long b) {
long long r = 1;
while (b) {
if (b & 1) r = a * r;
a = a * a;
b >>= 1;
}
return r;
}
inline long long gcd(long long a, long long b) {
while (b ^= a ^= b ^= a %= b)
;
return a;
}
inline long long lcm(long long a, long long b) { return a * b / gcd(a, b); }
inline long long inv(long long a, long long p) { return qpow(a, p - 2); }
const int maxn = 2e5 + 5;
struct node {
long long x, v;
friend bool operator<(node a, node b) {
return a.x == b.x ? a.v < b.v : a.x < b.x;
}
} a[maxn];
long long num[maxn << 2], sum[maxn << 2], ans, mx[maxn << 2];
void pushup(int rt) {
sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
num[rt] = num[rt << 1] + num[rt << 1 | 1];
mx[rt] = max(mx[rt << 1], mx[rt << 1 | 1]);
}
void modify(int l, int r, int rt, int pos, long long v, long long w) {
if (l == r) {
num[rt] += 1;
sum[rt] += v;
mx[rt] = w;
return;
}
int mid = l + r >> 1;
if (pos <= mid)
modify(l, mid, rt << 1, pos, v, w);
else
modify(mid + 1, r, rt << 1 | 1, pos, v, w);
pushup(rt);
}
long long query(int l, int r, int rt, long long v, long long w) {
if (l == r) {
if (mx[rt] <= v)
return abs(sum[rt] - num[rt] * w);
else
return 0;
}
int mid = l + r >> 1;
long long ret = 0;
ret += query(l, mid, rt << 1, v, w);
ret += query(mid + 1, r, rt << 1 | 1, v, w);
return ret;
}
int main() {
int n = read();
for (int i = 1; i <= n; i++) a[i].x = read();
for (int i = 1; i <= n; i++) a[i].v = read();
sort(a + 1, a + 1 + n);
for (int i = 1; i <= n; i++) {
ans += query(1, i, 1, a[i].v, a[i].x);
modify(1, n, 1, i, a[i].x, a[i].v);
}
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": []
}
|
IN-CORRECT
|
python3
|
n = int(input())
x = [int(a) for a in input().split()]
v = [int(a) for a in input().split()]
sum = 0
for i in range(1, n):
for j in range(i, n):
if x[j] < x[j-1]:
temp = x[j]
x[j] = x[j-1]
x[j-1] = temp
temp = v[j]
v[j] = v[j-1]
v[j-1] = temp
for i in range(n):
for j in range(i, n):
if v[j] > v[i]:
sum += x[j] - x[i]
print(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": []
}
|
IN-CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
List<Point> points = new ArrayList();
StringTokenizer st = new StringTokenizer(br.readLine());
long[] x = new long[n];
long[] vel = new long[n];
for(int i=0;i<n;i++){
x[i] = Long.parseLong(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
vel[i] = Long.parseLong(st.nextToken());
}
//HashMap<Long,Integer> velVal = getMap(vel);
for(int i=0;i<n;i++){
Point point = new Point(x[i],vel[i]);
points.add(point);
}
Collections.sort(points,(p1,p2)->{
if(p1.x< p2.x) return -1;
else if(p1.x == p2.x) return 0;
return 1;
});
Map<Long,Integer> map = getMap(points);
// points.stream().forEach(p->System.out.println(p.x+" "+p.vel));
long ans = 0;
int negX = 0;
int count = 0;
for(int i=0;i<points.size();i++){
if(points.get(i).vel < 0){
negX+=points.get(i).x;
count++;
}
else ans+= (count*points.get(i).x - negX);
}
Collections.sort(points,(p1,p2)->{
if(p1.vel< p2.vel) return -1;
else if(p1.vel == p2.vel) {
if(p1.x < p2.x)return -1;
else if(p1.x > p2.x) return 1;
return 0;
}
return 1;
});
//points.stream().forEach(p->System.out.println(p.x+" "+p.vel));
long[][] ft = new long[n+1][2];
int ind = -1;
for(int i=0;i<points.size();i++) {
if(points.get(i).vel >=0) {
ind = i;
break;
}
long[] res = BIT(ft,map,points.get(i).x);
long c = res[1];
long values = res[0];
ans+= (c*points.get(i).x-values);
//System.out.println("ans =" +ans);
}
ft = new long[n+1][2];
for(int i = (ind==-1) ? points.size() : ind; i< points.size(); i++) {
long[] res = BIT(ft,map,points.get(i).x);
long c = res[1];
long values = res[0];
ans+= (c*points.get(i).x-values);
//System.out.println("ans =" +ans);
}
out.println(ans);
out.close();
}
private static Map<Long,Integer> getMap(List<Point> points){
Map<Long,Integer> map = new HashMap();
int pos=1,neg = 1;
for(int i=0;i<points.size();i++) {
if(points.get(i).vel < 0) {
map.put(points.get(i).x, neg);
neg++;
}
else {
map.put(points.get(i).x, pos);
pos++;
}
}
return map;
}
public static long[] BIT(long[][] ft, Map<Long,Integer> map,long val){
int v = map.get(val);
long[] result = new long[2];
result[0]+=ft[v][0];
result[1]+=ft[v][1];
while(v > 0){
v -= ((~v) + 1)&v;
result[0]+=ft[v][0];
result[1]+=ft[v][1];
}
v = map.get(val);
while(v < ft.length){
ft[v][0]+=val;
ft[v][1]++;
v += ((~v) + 1)&v;
}
return result;
}
}
class Point{
long x;
long vel;
Point(long x, long vel){
this.x= x;
this.vel = vel;
}
}
|
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": []
}
|
IN-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(n), neg = new bit(n);
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++;
int v = nee.get(MX + x[i][1]);
ans += negcnt.query(v) * (long) x[i][0] - neg.query(v);
negcnt.modify(v, 1);
neg.modify(v, x[i][0]);
cneg += x[i][0];
} else {
cntz++;
cz += x[i][0];
ans += cneg;
}
}
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 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);
}
}
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": []
}
|
IN-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};
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());
reverse(v.begin(), v.end());
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 * 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": []
}
|
IN-CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class f_624_Div3
{
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;
}
}
public static void print(int[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
static int sorted_size;
static long[] prefixsum;
static long[] prefixcount;
static int[] points;
static int[] speeds;
static int n;
static int n_speeds;
public static void main(String[] args)
{
FastReader io = new FastReader();
n = io.nextInt();
points = new int[n];
speeds = new int[n];
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
points[i] = io.nextInt();
}
for(int i=0;i<n;i++){
speeds[i] = io.nextInt();
map.putIfAbsent(points[i],speeds[i]);
}
Arrays.sort(points);
for(int i=0;i<n;i++){
speeds[i] = map.get(points[i]);
}
map.clear();
//now we need to sort
int [] sorted_speeds = speeds.clone();
Arrays.sort(sorted_speeds);
HashSet<Integer> hs = new HashSet<>();
for(int i=0;i<n;i++){
hs.add(sorted_speeds[i]);
}
sorted_speeds = new int[hs.size()];
Iterator<Integer> itr = hs.iterator();
int i=0;
while (itr.hasNext()){
sorted_speeds[i++] = itr.next();
}
Arrays.sort(sorted_speeds);
sorted_size = sorted_speeds.length;
n_speeds = sorted_size;
//now we have sorted speeds we need to create a prefixsum and prefix count
prefixsum = new long[sorted_size+1];
prefixcount = new long[sorted_size+1];
// print(sorted_speeds);
long answer =0;
for(i=0;i<n;i++){
int pos = Arrays.binarySearch(sorted_speeds,speeds[i]);
int count = query_count(pos);
int sum = query_sum(pos);
answer+=((count*points[i]*1L)-sum);
update(pos,points[i]);
}
System.out.println(answer);
}
static void update(int x, int delta)
{ x++;
for(; x <= n_speeds; x += x&-x){
prefixsum[x] += delta;
prefixcount[x]+=1;
}
}
static int query_count(int x)
{ x++;
int sum = 0;
for(; x > 0; x -= x&-x)
sum += prefixcount[x];
return sum;
}
static int query_sum(int x)
{ x++;
int sum = 0;
for(; x > 0; x -= x&-x)
sum += prefixsum[x];
return sum;
}
// OutputStream out = new BufferedOutputStream( System.out );
// for(int i=1;i<n;i++){
// out.write((max_divisor[i]+" ").getBytes());
//}
// out.flush();
}
|
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": []
}
|
IN-CORRECT
|
java
|
//package Round624;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
/**
* @author sguar <shugangcao@gmail.com>
* strive for greatness
* Created on 2020-01-10
*/
public class E {
InputStream is;
PrintWriter out;
private static final String INPUT_FILE_NAME = "/Users/sguar/IdeaProjects/kotlinLearn/src/input.txt";
void solve() {
int n = ni();
int[] x = na(n);
int[] v = na(n);
Pair[] pairs = new Pair[n];
for (int i = 0; i < n; i++) {
pairs[i] = new Pair(i, x[i]);
}
Arrays.sort(pairs, Comparator.comparingInt(o -> o.y));
Map<Integer, Integer> xMap = new HashMap<>();
Pair[] points = new Pair[n];
int cnt = 0;
for (int i = 0; i < n; i++) {
Pair p = pairs[i];
if (!xMap.containsKey(p.y)) {
xMap.put(++cnt, p.y);
}
points[i] = new Pair(cnt, v[pairs[i].x]);
}
Arrays.sort(points, (o1, o2) -> {
if (o1.y == o2.y) {
return o1.x - o2.x;
}
return o1.y - o2.y;
});
debug(xMap);
debug(points);
BIT bit = new BIT(n);
long ans = 0;
for (int i = 0; i < n; i++) {
Pair p = points[i];
int realX = xMap.get(p.x);
ans += bit.query(p.x, realX);
bit.add(p.x, realX);
}
out.println(ans);
}
public class BIT {
int n;
long[] a;
int[] cnt;
BIT(int n) {
this.n = n;
this.a = new long[n << 1];
this.cnt = new int[n << 1];
}
int lowBit(int x) {
return x & (-x);
}
void add(int index, int cnt) {
while (index <= this.n) {
this.a[index] += cnt;
this.cnt[index] += 1;
index += lowBit(index);
}
}
long query(int index, int now) {
long sum = 0;
while (index > 0) {
sum += this.cnt[index] * now - this.a[index];
index = index - lowBit(index);
}
return sum;
}
}
class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "x: " + x + ", y: " + y;
}
}
public static long invl(long a, long mod) {
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
return p < 0 ? p + mod : p;
}
void run() throws Exception {
is = oj ? System.in : new FileInputStream(INPUT_FILE_NAME);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
debug(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new E().run();
}
private byte[] inbuf = new byte[1024];
int lenbuf = 0;
int ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void debug(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
private void debug(Map map) {
if (!oj) {
if (map.isEmpty()) {
System.out.println("map is empty");
} else {
map.forEach(this::debug);
}
}
}
private void debug(Object k, Object v) {
if (!oj) {
System.out.println(k.toString() + ": " + v.toString());
}
}
}
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
///#pragma GCC target ("sse,sse2,sse3,ssse3,sse4,avx,sse4.1,sse4.2,mmx")
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize ("Ofast")
#pragma GCC optimize ("O3")
using namespace std;
using namespace __gnu_pbds;
#define int long long
#define ff first
#define ss second
#define db double
#define auf true
#define pb push_back
#define what(x) cerr << #x << " = " << x << '\n'
const int N = 1e6 + 5, M = 3e3 + 5;
const int inf = 1e18 + 100, mod = 1e9 + 7;
const db eps = 1e-9;
typedef tree < pair < int, int >, null_type, less < pair < int, int > >, rb_tree_tag, tree_order_statistics_node_update > ordered_set;
typedef tree < int, null_type, less_equal < int >, rb_tree_tag, tree_order_statistics_node_update > ordered_multiset;
mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
int rnd(int l, int r){
return mt_rnd_64() % (r - l + 1) + l;
}
pair < int, int > p[N];
ordered_set s;
signed main()
{
// #ifndef _WIN32
// freopen("lz.in", "r", stdin);
// freopen("lz.out", "w", stdout);
// #endif
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> p[i].ff;
for (int i = 1; i <= n; ++i)
cin >> p[i].ss;
sort(p + 1, p + n + 1);
int ans = 0;
for (int i = 1; i <= n; ++i)
{
int cnt = s.order_of_key({p[i].ss, 0});
ans += cnt * p[i].ff;
s.insert({p[i].ss, i});
}
s.clear();
for (int i = n; i >= 1; --i)
{
int cnt = (int)s.size() - s.order_of_key({p[i].ss - 1, n + 1});
ans -= cnt * p[i].ff;
s.insert({p[i].ss, i});
}
cout << ans;
return 0;
}
/// hto ya? zvychayna domohospodarka chy president Ykrainy?
/// οΏ½οΏ½οΏ½)
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
constexpr int maxN = 2e5 + 43;
int n;
vector<pair<int, int>> point;
vector<int> val, cnt, cval;
int LSOne(int k) { return (k & (-k)); }
void update(vector<int>& f, int pos, int val) {
for (; pos <= n; pos += LSOne(pos)) f[pos] += val;
}
long long rsq(vector<int>& f, int pos) {
long long sum = 0;
for (; pos; pos -= LSOne(pos)) sum += f[pos];
return sum;
}
bool Comp(const pair<int, int>& a, const pair<int, int>& b) {
return a.first < b.first;
}
int 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 (int i = 1; i <= n; ++i) {
cin >> point[i].first;
}
for (int i = 1; i <= n; ++i) {
cin >> point[i].second;
val[i] = point[i].second;
}
sort(point.begin() + 1, point.begin() + n + 1, Comp);
sort(val.begin(), val.begin() + n + 1);
long long ans = 0;
for (int i = 1; i <= n; ++i) {
int pos =
lower_bound(val.begin() + 1, val.begin() + n + 1, point[i].second) -
val.begin();
ans += rsq(cnt, pos - 1) * point[i].first - rsq(cval, pos - 1);
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long mx = 2 * 1e5 + 5;
const long long mod = 1e9 + 7;
pair<long long, long long> arr[mx * 4];
void update(int node, int left, int right, int pos, long long val) {
if (left == right) {
arr[node].first++;
arr[node].second += val;
return;
}
int mid = (left + right) / 2;
if (pos <= mid) {
update(node * 2, left, mid, pos, val);
} else {
update(node * 2 + 1, mid + 1, right, pos, val);
}
arr[node].first = arr[node * 2].first + arr[node * 2 + 1].first;
arr[node].second = arr[node * 2].second + arr[node * 2 + 1].second;
return;
}
pair<long, long> sum(pair<long long, long long> a,
pair<long long, long long> b) {
return {a.first + b.first, a.second + b.second};
}
pair<long long, long long> query(int node, int left, int right, int l, int r) {
if (right < l || left > r) {
return {0, 0};
}
if (right <= r && left >= l) {
return {arr[node].first, arr[node].second};
}
int mid = (left + right) / 2;
return sum(query(node * 2, left, mid, l, r),
query(node * 2 + 1, mid + 1, right, l, r));
}
int main() {
int n;
cin >> n;
pair<long long, long long> p[n + 1];
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 = 0;
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++) {
int myv = p[i].second;
int myx = p[i].first;
pair<int, int> cnt = query(1, 0, n, 0, myv);
ans += (1LL * myx * cnt.first);
ans -= cnt.second;
update(1, 0, n, myv, myx);
}
update(1, 0, n, 0, 5);
pair<int, int> cnt = query(1, 0, n - 1, 0, 0);
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ll long long
#define FI first
#define SE second
#define pb push_back
#define eb emplace_back
#define mod 1000000007
#define all(c) (c).begin(),(c).end()
#define LB lower_bound
#define UB upper_bound
#define max3(a,b,c) max(c,max(a,b))
#define min3(a,b,c) min(c,min(a,b))
#define mems(s, n) memset(s, n, sizeof(s))
#define NINF INT_MIN
#define INF INT_MAX
#define int ll int
#define OOK order_of_key //no of elements less than
#define FBO find_by_order //iterator pointing kth element;indexing starts from 0
#define CK3(x,y,z) cout<<(x)<<" "<<(y)<<" "<<(z)<<endl
#define CK4(a,b,c,d) cout<<(a)<<" "<<(b)<<" "<<(c)<<" "<<(d)<<endl
typedef pair<int,int> PII;
typedef pair<pair<int,int>,int> PPII;
typedef map<int,PII>MII;
typedef vector<int> VI;
template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
/*int power(int a, int b)
{int x=1,y=a;while(b>0){if(b%2){x =(x*y)%mod;}y =(y*y)%mod;b/=2;}return x%mod;}
*/
//int modInverse(int a, int m) {return power(a, m-2);} //gcd(a,m)=1
//int root(int x){return x==f[x]?x:f[x]=root(f[x]);}
MII t;
/*void build( int v, int tl, int tr) {
if (tl == tr) {
t[v] = a[tl];
} else {
int tm = (tl + tr) / 2;
build(a, v*2, tl, tm);
build(a, v*2+1, tm+1, tr);
t[v] = t[v*2] + t[v*2+1];
}
}
int sum(int v, int tl, int tr, int l, int r) {
if (l > r)
return 0;
if (l == tl && r == tr) {
return t[v];
}
int tm = (tl + tr) / 2;
return sum(v*2, tl, tm, l, min(r, tm))
+ sum(v*2+1, tm+1, tr, max(l, tm+1), r);
}
*/
void update(int v, int tl, int tr, int l, int r, int add,int r1) {
if (l > r)
return;
if (l == tl && r == tr) {
t[v].FI += add,t[v].SE+=r1;
} else {
int tm = (tl + tr) / 2;
update(v*2, tl, tm, l, min(r, tm), add,(int)r1);
update(v*2+1, tm+1, tr, max(l, tm+1), r, add,(int)r1);
}
}
PII get(int v, int tl, int tr, int pos) {
if (tl == tr)
return t[v];
int tm = (tl + tr) / 2;
if (pos <= tm)
{PII hp=get(v*2, tl, tm, pos);return {t[v].FI + hp.FI,t[v].SE +hp.SE};}
else
{PII hp=get(v*2+1, tm+1, tr, pos); return {t[v].FI + hp.FI,t[v].SE + hp.SE};}
}
signed main()
{
ios::sync_with_stdio(false); cin.tie(0);
int T=1,T1=0;//cin>>T;
while(T1++<T)
{
int n;
cin>>n;int ans=0;vector<PII>ar(n);
for(int i=0;i<n;i++)
{
cin>>ar[i].FI;
}
for(int i=0;i<n;i++)
{
cin>>ar[i].SE;ar[i].SE+=100000000;
update(1,0,200000005,ar[i].SE,200000005,ar[i].FI,(int)1);
}
sort(all(ar));
int sum1=0;
for(int i=0;i<n;i++)
{ sum1+=ar[i].FI;
PII x=get(1,0,200000005,ar[i].SE-1);
//cout<<x.FI<<" "<<x.SE<<" ";
x.FI=(n*(n+1))/2-sum1-x.FI;x.SE=n-i-1-x.SE;
//cout<<x.FI-ar[i].FI*x.SE<<endl;
ans+=max((int)0,x.FI-ar[i].FI*x.SE);
update(1,0,200000005,ar[i].SE,200000005,-ar[i].FI,(int)-1);
}
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
int x[100010 * 2], v[100010 * 2];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &v[i]);
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (x[i] < x[j]) {
if (v[i] > v[j])
continue;
else
ans += x[j] - x[i];
} else if (x[i] > x[j]) {
if (v[j] > v[i])
continue;
else
ans += x[i] - x[j];
} else
continue;
}
}
printf("%d", 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": []
}
|
IN-CORRECT
|
java
|
import java.math.*;
import java.io.*;
import java.util.*;
import java.awt.*;
public class Main implements Runnable {
@Override
public void run() {
try {
new Solver().solve();
System.exit(0);
} catch (Exception | Error e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
//new Thread(null, new Main(), "Solver", 1l << 25);
new Main().run();
}
}
class Solver {
final Helper hp;
final int MAXN = 10_004;
final long MOD = (long) 1e9 + 7;
final Timer timer;
final TimerTask task;
Solver() {
hp = new Helper(MOD, MAXN);
hp.initIO(System.in, System.out);
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
try {
hp.flush();
System.exit(0);
} catch (Exception e) {
}
}
};
//timer.schedule(task, 4700);
}
void solve() throws Exception {
int i, j, k;
boolean testCases = true;
int tc = testCases ? hp.nextInt() : 1;
for (int tce = 1; tce <= tc; tce++) {
int N = hp.nextInt(), D = hp.nextInt();
int[] parent = solve(N, D);
if (parent == null) {
hp.println("NO");
} else {
hp.println("YES");
for (i = 1; i < N; ++i) hp.printsp(parent[i] + 1);
hp.println();
}
}
timer.cancel();
hp.flush();
}
HashMap<Long, int[]> mem = new HashMap<>();
int[] solve(int n, int d) {
if (n < 0 || d < 0) return null;
//System.err.println(n + " " + d + " -> ");
final long hash = n * MAXN + d;
if (d == 0) return n <= 1 ? new int[] {-7} : null;
else if (mem.containsKey(hash)) return mem.get(hash);
int upperBound = n * (n - 1) >> 1, lowerBound = 0;
for (int i = 0, tmp = n; tmp > 0; ++i) {
lowerBound += Math.min(tmp, 1 << i) * i;
tmp -= 1 << i;
}
//System.err.println(lowerBound + " " + upperBound);
if (d < lowerBound || d > upperBound) {
mem.put(hash, null);
return null;
}
int[] parent = new int[n];
Arrays.fill(parent, -7);
if (d == lowerBound) {
for (int i = 1; i < n; ++i) parent[i] = i - 1 >> 1;
mem.put(hash, Arrays.copyOf(parent, parent.length));
return parent;
} else if (d == upperBound) {
for (int i = 1; i < n; ++i) parent[i] = i - 1;
mem.put(hash, Arrays.copyOf(parent, parent.length));
return parent;
} else {
for (int l = 1; l <= n; ++l) {
//int l = 3; {
int r = n - 1 - l;
for (int x = 1; x <= d; ++x) {
//int x = 6; {
int y = d - x;
int[] left = solve(l, x - l), right = solve(r, y - r);
if (left != null && right != null) {
left[0] = right[0] = 0;
for (int i = 1; i < l; ++i) left[i] += 1;
for (int i = 1; i < r; ++i) right[i] += l + 1;
int k = 1;
for (int i = 0; i < l; ++i) parent[k++] = left[i];
for (int i = 0; i < r; ++i) parent[k++] = right[i];
mem.put(hash, Arrays.copyOf(parent, parent.length));
return parent;
}
}
}
mem.put(hash, null);
return null;
}
}
}
class Helper {
final long MOD;
final int MAXN;
final Random rnd;
public Helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
public static long[] factorial;
public void setFactorial() {
factorial = new long[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;
}
public long getFactorial(int n) {
if (factorial == null) setFactorial();
return factorial[n];
}
public long ncr(int n, int r) {
if (r > n) return 0;
if (factorial == null) setFactorial();
long numerator = factorial[n];
long denominator = factorial[r] * factorial[n - r] % MOD;
return numerator * pow(denominator, MOD - 2, MOD) % MOD;
}
public long[] getLongArray(int size) throws Exception {
long[] ar = new long[size];
for (int i = 0; i < size; ++i) ar[i] = nextLong();
return ar;
}
public int[] getIntArray(int size) throws Exception {
int[] ar = new int[size];
for (int i = 0; i < size; ++i) ar[i] = nextInt();
return ar;
}
public String[] getStringArray(int size) throws Exception {
String[] ar = new String[size];
for (int i = 0; i < size; ++i) ar[i] = next();
return ar;
}
public String joinElements(long... ar) {
StringBuilder sb = new StringBuilder();
for (long itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(int... ar) {
StringBuilder sb = new StringBuilder();
for (int itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(String... ar) {
StringBuilder sb = new StringBuilder();
for (String itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(Object... ar) {
StringBuilder sb = new StringBuilder();
for (Object itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public long max(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.max(ret, itr);
return ret;
}
public int max(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.max(ret, itr);
return ret;
}
public long min(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.min(ret, itr);
return ret;
}
public int min(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.min(ret, itr);
return ret;
}
public long sum(long... ar) {
long sum = 0;
for (long itr : ar) sum += itr;
return sum;
}
public long sum(int... ar) {
long sum = 0;
for (int itr : ar) sum += itr;
return sum;
}
public void shuffle(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void shuffle(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
static final int BUFSIZE = 1 << 20;
static byte[] buf;
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String next() throws Exception {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan())
sb.append((char) c);
return sb.toString();
}
public int nextInt() throws Exception {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long nextLong() throws Exception {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public void print(Object a) throws Exception {
bw.write(a.toString());
}
public void printsp(Object a) throws Exception {
print(a);
print(" ");
}
public void println() throws Exception {
bw.write("\n");
}
public void println(Object a) throws Exception {
print(a);
println();
}
public void flush() throws Exception {
bw.flush();
}
}
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct Node {
int l, r;
int cnt = 0;
long long sum = 0;
int left = -1;
int right = -1;
} NIL;
vector<Node> st;
Node merge(Node x, Node y) {
Node z;
z.cnt = x.cnt + y.cnt;
z.sum = x.sum + y.sum;
return z;
}
void add(int u, int x, int v) {
if (not(st[u].l <= v and v <= st[u].r)) return;
if (st[u].l == v and v == st[u].r) {
st[u].cnt += 1;
st[u].sum += x;
return;
}
int m = (st[u].l + st[u].r) >> 1;
if (st[u].left == -1) {
Node x;
x.l = st[u].l, x.r = m;
st[u].left = int(st.size());
st.push_back(x);
}
if (st[u].right == -1) {
Node x;
x.l = m + 1, x.r = st[u].r;
st[u].right = int(st.size());
st.push_back(x);
}
add(st[u].left, x, v);
add(st[u].right, x, v);
Node s = merge(st[st[u].left], st[st[u].right]);
st[u].sum = s.sum;
st[u].cnt = s.cnt;
};
Node gteq(int u, int L, int R) {
if (u == -1 or st[u].r < L or R < st[u].l) return NIL;
if (L <= st[u].l and st[u].r <= R) return st[u];
return merge(gteq(st[u].left, L, R), gteq(st[u].right, L, R));
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<pair<int, int> > p(n);
for (int i = 0; i < n; i++) cin >> p[i].first;
for (int i = 0; i < n; i++) cin >> p[i].second;
sort(begin(p), end(p));
Node root;
root.l = -1e8;
root.r = 1e8;
st.emplace_back(root);
long long ans = 0;
for (int i = n - 1; i >= 0; i--) {
Node s = gteq(0, p[i].second, 1e8);
ans += s.sum - s.cnt * p[i].first;
add(0, p[i].first, p[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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long n, a1[202020], a2[202020], od[202020];
pair<int, int> p[202020];
long long ans;
map<int, int> mp;
void gx1(int x, int v) {
for (int i = x; i < 200200; i += i & -i) {
a1[i] += v;
}
}
void gx2(int x, int v) {
for (int i = x; i < 200200; i += i & -i) {
a2[i] += v;
}
}
int gt1(int p) {
long long rt = 0;
for (int i = p; i > 0; i -= i & -i) {
rt += a1[i];
}
return rt;
}
int gt2(int p) {
long long rt = 0;
for (int i = p; i > 0; i -= i & -i) {
rt += a2[i];
}
return rt;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> p[i].first;
}
for (int 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);
int pp = 1;
for (int i = 1; i <= n; i++) {
if (!mp[od[i]]) {
mp[od[i]] = pp;
pp++;
}
}
for (int i = 1; i <= n; i++) {
ans += 1ll * p[i].first * gt1(mp[p[i].second]) - 1ll * gt2(mp[p[i].second]);
gx1(mp[p[i].second], 1);
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": []
}
|
IN-CORRECT
|
java
|
import java.io.*;
import java.util.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Housni Abdellatif
*/
public class Main {
public static void main(String[] args) throws IOException{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Task.Reader in = new Task.Reader();
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, Reader reader, PrintWriter out) throws IOException {
int n = reader.nextInt();
Point[] pts = new Point[n];
List<Integer> vs = new ArrayList<>();
for (int i = 0; i < n; ++i) {
pts[i] = new Point();
pts[i].x = reader.nextInt();
}
for (int i = 0; i < n; ++i) {
int v = reader.nextInt();
pts[i].v = v;
vs.add(v);
}
Collections.sort(vs);
Arrays.sort(pts, (p1, p2) -> p1.x - p2.x);
long ans = 0;
int[] bitV = new int[n];
int[] bitX = new int[n];
for (int i = 0; i < n; ++i) {
int pos = getFirstIndex(vs, pts[i].v);
long cnt = sum(bitV, pos);
long s = sum(bitX, pos);
//out.println(s);
ans += cnt * pts[i].x - s;
update(bitV, pos, 1);
update(bitX, pos, pts[i].x);
}
out.println(ans);
}
private void update(int[] bit, int index, int delta) {
while (index < bit.length) {
bit[index] += delta;
index |= (index + 1);
}
}
private long sum(int[] bit, int r) {
long res = 0;
while (r >= 0) {
res += bit[r];
r = (r & (r + 1)) - 1;
}
return res;
}
private int getFirstIndex(List<Integer> list, int x) {
int l = 0;
int r = list.size() - 1;
while ( l < r) {
int m = (l + r) / 2;
if (list.get(m) < x) {
l = m + 1;
}else {
r = m;
}
}
return l;
}
static class Point {
int x;
int v;
}
static 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]; // line length
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": []
}
|
IN-CORRECT
|
java
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class cf {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++) {
arr[i] = input.nextInt();
}
int arr_v[] = new int[n];
for(int i=0;i<n;i++) {
arr_v[i] = input.nextInt();
}
int res = 0;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
// System.out.println("x1 = "+arr[i]+" x2 = "+arr[j]+" v1 = "+arr_v[i]+" v2 = "+arr_v[j]);
// System.out.println(mp(arr[i],arr[j],arr_v[i],arr_v[j]));
res+=mp(arr[i],arr[j],arr_v[i],arr_v[j]);
}
}
System.out.println(res);
}
static int mp(int x1,int x2,int v1,int v2) {
if((x2>x1 && v2>v1) || (x1>x2 && v1>v2) || (v1==v2)) {
return Math.abs(x2-x1);
}
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": []
}
|
IN-CORRECT
|
java
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class p6
{
static class Input {
private StringTokenizer tokenizer = null;
private BufferedReader reader;
public Input(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException();
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] nextIntArray(int n, int add) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = nextInt() + add;
}
return result;
}
public long[] nextLongArray(int n, long add) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = nextLong() + add;
}
return result;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
}
static int get(int a[],int in)
{
int sum=0;
while(in>0)
{
sum+=a[in];
in-=in&(-in);
}
return sum;
}
static void upd(int a[],int in ,int val)
{
int n=a.length-1;
while(in<=n)
{
a[in]+=val;
in+=in&(-in);
}
}
static PrintWriter out=new PrintWriter(System.out);
static int search(int a[],int e)
{
//out.println("ele"+e);
int l=0,r=a.length-1,mid,ans=r;
while(l<=r)
{
mid=(l+r)/2;
// out.println(l+" "+r+" "+a[mid]);
if(a[mid]>=e)
{
ans=Math.min(ans,mid);
r=mid-1;
}
else
l=mid+1;
}
// out.println(ans);
return ans;
}
public static void main (String[] args) throws java.lang.Exception
{
Input s=new Input(System.in);
int t=1;
while(t-->0)
{
int n=s.nextInt();
int a[]=s.nextIntArray(n);
int b[]=s.nextIntArray(n);
myclass m1[]=new myclass[n];
TreeSet<Integer> hs=new TreeSet<>();
for(int i=0;i<n;i++)
{
m1[i]=new myclass(a[i],b[i]);
hs.add(b[i]);
}
Arrays.sort(m1,new myclass());
int c[]=new int[hs.size()];
int i1=0;
for(Integer el:hs)
c[i1++]=el;
int p1[]=new int[hs.size()+1];
int p2[]=new int[hs.size()+1];
long ans=0;
for(int i=0;i<n;i++)
{
int in=search(c,m1[i].b);
//out.println(get(p1,in+1)+" "+get(p2,in+1));
ans+=get(p1,in+1)*m1[i].a-get(p2,in+1);
upd(p1,in+1,1);
upd(p2,in+1,m1[i].a);
// out.println(m1[i].b+" "+ans+" "+in);
}
out.println(ans);
}
out.flush();
}
}
class myclass implements Comparator<myclass>
{
int a,b;
myclass(int a,int b)
{
this.a=a;
this.b=b;
}
myclass(){}
public int compare(myclass m1,myclass m2)
{
if(m1.a!=m2.a)
return m1.a-m2.a;
else
return m1.b-m2.b;
}
}
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
using LL = long long int;
template <class T>
struct Binary_Indexed_Tree {
int maxSize;
T* data;
Binary_Indexed_Tree(int init_Size) : maxSize(init_Size) {
data = new T[maxSize + 5];
memset(data, 0, sizeof(T) * (maxSize + 5));
}
~Binary_Indexed_Tree() { delete[] data; }
void add(int loc, T val) {
while (loc < maxSize) {
data[loc] += val;
loc += (loc & (-loc));
}
return;
}
T query(int loc) {
T ans = 0;
while (loc > 0) {
ans += data[loc];
loc -= (loc & (-loc));
}
return ans;
}
};
struct point {
LL x, v;
point(LL x_ = 0, LL v_ = 0) : x(x_), v(v_) {}
bool operator<(const point& b) { return x < b.x; }
};
const int maxn = 2e5 + 5;
point p[maxn];
int n = 0, v[maxn];
int main(void) {
scanf("%d", &n);
for (int i = 0; i < n; ++i)
scanf("%lld", &p[i].x);
for (int i = 0; i < n; ++i) {
scanf("%lld", &p[i].v);
v[i] = p[i].v;
}
sort(p, p + n);
sort(v, v + n);
int cnt = unique(v, v + n) - v;
auto getid = [=](LL val) { return lower_bound(v, v + cnt, val) - v + 1; };
Binary_Indexed_Tree<LL> c(n);
Binary_Indexed_Tree<LL> x(n);
LL ans = 0;
for (int i = 0; i < n; ++i) {
LL id = getid(p[i].v);
LL cnt = c.query(id);
LL sum = x.query(id);
ans += (cnt * p[i].x - sum);
c.add(id, 1);
x.add(id, 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": []
}
|
IN-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
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class F
{
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[] post = readArr(N, infile, st);
int[] vel = readArr(N, infile, st);
//compress vel
int boof = compress(vel);
Point[] arr = new Point[N];
for(int i=0; i < N; i++)
arr[i] = new Point(post[i], vel[i]);
//sort by location
Arrays.sort(arr);
FenwickTree pos = new FenwickTree(boof+2);
FenwickTree pc = new FenwickTree(boof+2);
FenwickTree neg = new FenwickTree(boof+2);
FenwickTree nc = new FenwickTree(boof+2);
long res = 0L;
for(Point p: arr)
{
if(p.vel < 0)
{
long temp = nc.find((int)p.vel, boof)*p.pos;
temp -= neg.find((int)p.vel, boof);
temp += pos.find(1, boof)-pc.find((int)p.vel, boof)*p.pos;
nc.add((int)p.pos, 1);
neg.add((int)p.vel, p.pos);
res += temp;
}
else
{
long temp = pc.find((int)p.vel, boof)*p.pos;
temp -= pos.find((int)p.vel, boof);
temp += neg.find(1, boof)-nc.find((int)p.vel, boof)*p.pos;
pc.add((int)p.pos, 1);
pos.add((int)p.vel, p.pos);
res += temp;
}
}
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 int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
class Point implements Comparable<Point>
{
public long pos;
public long vel;
public Point(long a, long b)
{
pos = a;
vel = b;
}
public int compareTo(Point oth)
{
/*
if(oth.vel == vel)
return (int)(pos-oth.pos);
return (int)(vel-oth.vel);
*/
return (int)(vel-oth.vel);
}
}
class FenwickTree
{
//1 indexed
public long[] tree;
public int size;
public FenwickTree(int size)
{
this.size = size;
tree = new long[size+5];
}
public void add(int i, long v)
{
while(i <= size)
{
tree[i] += v;
i += i&-i;
}
}
public long find(int i)
{
long res = 0L;
while(i >= 1)
{
res += tree[i];
i -= i&-i;
}
return res;
}
public long find(int l, int r)
{
return find(r)-find(l-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": []
}
|
IN-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);
}
seg.build(initializer);
sort(xs.begin(), xs.end());
for (int j = 0; j < m; ++j) seg.update(xs[j].second, {ps[i][j].second, 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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long N = 3e5 + 5;
pair<long long, long long> p[N], a[N];
long long n;
long long fwt[N], cntf[N];
long long len;
void add(long long *b, long long x, long long v) {
while (x <= len) {
b[x] += v;
x += x & -x;
}
}
long long get(long long *b, long long x) {
long long res = 0;
while (x) {
res += b[x];
x -= x & -x;
}
return res;
}
signed main() {
ios::sync_with_stdio(false);
cin >> n;
vector<long long> velo_neg, velo_pos;
for (long long i = 0; i < n; i++) {
cin >> p[i].first;
}
for (long long i = 0; i < n; i++) {
cin >> p[i].second;
}
sort(p, p + n);
vector<long long> velo;
for (long long i = 0; i < n; i++) {
velo.push_back(p[i].second);
}
sort(velo.begin(), velo.end());
velo.erase(unique(velo.begin(), velo.end()), velo.end());
len = velo.size();
long long ans = 0;
long long sumx = 0;
for (long long i = 0; i < n; i++) {
a[i] = p[i];
a[i].second =
lower_bound(velo.begin(), velo.end(), p[i].second) - velo.begin() + 1;
ans += i * p[i].first - sumx;
sumx += p[i].first;
}
for (long long i = 0; i < n; i++) {
if (p[i].second < 0) {
ans -= (get(cntf, len) - get(cntf, a[i].second)) * p[i].first -
(get(fwt, len) - get(fwt, a[i].second));
}
add(fwt, a[i].second, p[i].first);
add(cntf, a[i].second, 1);
}
memset(cntf, 0, sizeof cntf);
memset(fwt, 0, sizeof fwt);
for (long long i = n - 1; i >= 0; i--) {
if (p[i].second > 0) {
ans -=
get(fwt, a[i].second - 1) - get(cntf, a[i].second - 1) * p[i].first;
}
if (p[i].second > 0) {
add(fwt, a[i].second, p[i].first);
add(cntf, a[i].second, 1);
}
}
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": []
}
|
IN-CORRECT
|
java
|
//package psa.minrazdalja;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class minrazdalja {
/**
* Uvozena abstraktna funkcija za klic Paid<L, R>
*/
public static class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
/**?
* glavna funkcija racunanja:
* sprejme list tipa ArrayList<Pair<Integer, Integer>>, potem st vseh elementov in seveda listo vseh elementov.
*
* nato izracunamo maksimalno distance, ki je sestevek vseh distanc med posameznimi elementi, kar lahko storimo, ker je sortirana tabela.
* V drugem delu odstejemo od maksimalnega sestevka distanc, posamezne ki se sekajo v prihodnosti
* ostane nam samo tocni sestevek minimalnih distanc
*/
public static long elele(ArrayList<Pair<Long,Long>> elementi, int s, Long[] x_el) {
long skupek = 0;
HashMap<Long, Integer> pos = new HashMap<Long, Integer>();
for(int i=0; i<s; ++i) {
skupek += x_el[i] * i + (-1 * x_el[i]) * (s - 1 - i);
pos.put(x_el[i], i);
}
//if(s == 161)
// System.out.println(skupek);
for(int i=0; i<s; ++i){
skupek -= elementi.get(i).getRight() * ( pos.get(elementi.get(i).getRight()) - i );
}
//2 1 4 3 5
//2 2 2 3 4
return skupek;
}
public static void main(String[] args) throws IOException {
int st_el;
// uporabimo bufferedreader zaradi 1000x vecje hitrosti kot pa skener
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//System.out.println("Vnesi stevilo elementov: ");
st_el = Integer.parseInt(br.readLine());
//System.out.println(st_el);
Long[] x_el = new Long[st_el];
Long[] v_el = new Long[st_el];
//System.out.println("Vnesi elemente: ");
String x = br.readLine();
String[] strs = x.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
x_el[i] = Long.parseLong(strs[i]);
}
//System.out.println("Vnesi tezo elementov: ");
String y = br.readLine();
String[] strs2 = y.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
v_el[i] = Long.parseLong(strs2[i]);
}
br.close();
//pospravimo skupej v par oblike <integer, integer> oz <hitrost, element>
ArrayList<Pair<Long,Long>> listt = new ArrayList<Pair<Long, Long>>(st_el);
for(int i=0; i<st_el; i++) {
Pair<Long, Long> pair = new Pair<Long, Long>(v_el[i],x_el[i]);
listt.add(pair);
}
/*sortiramo listt od najmanjsega do najvecjega
* - sortiramo prvo po hitrostih (to je glavno najbolj vazno)
* - ce je hitrost ista potem pa sortiramo se glede na element
*/
Collections.sort(listt, new Comparator<Pair<Long, Long>>() {
@Override
public int compare(final Pair<Long, Long> o1, final Pair<Long, Long> o2) {
if(o1.getLeft()<o2.getLeft()) {
return -1;
} else if(o1.getLeft() == o2.getLeft()) {
if(o1.getRight() < o2.getRight()){
return -1;
}else{
return 1;
}
} else {
return 1;
}
}
});
//sortiramo se elemente
Arrays.sort(x_el);
//izpisemo elemente
System.out.println(elele(listt,st_el,x_el));
}
}
|
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": []
}
|
IN-CORRECT
|
java
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class ct1{
static class Point{
int ip, speed;
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int a = inp.nextInt();
Point[] points = new Point[a];
for (int l=0; l<a; l++){
// int a = inp.nextInt();
for (int i=0; i<a; i++){
points[i] = new Point();
}
for (int i=0; i<a; i++){
if (inp.hasNextInt())
points[i].ip = inp.nextInt();
}
for (int i=0; i<a; i++){
if (inp.hasNextInt())
points[i].speed = inp.nextInt();
}
int ans=0;
for (int i=0; i<a-1; i++){
for (int j=i+1; j<a; j++){
if (points[i].ip < points[j].ip){
if(points[i].speed <= points[j].speed){
ans+=points[j].ip - points[i].ip;
}
}
else if(points[i].ip == points[j].ip)
ans+=0;
else {
if(points[i].speed >= points[j].speed){
ans+=points[i].ip - points[j].ip;
}
}
}
}
System.out.println(ans);
}
}
// static class ArrivalBurst{
// public int arrivalTime, burstTime, waitingTime, turnAroundTime, completionTime;
// ArrivalBurst(){
// arrivalTime =0;
// burstTime =0;
// waitingTime =0;
// turnAroundTime =0;
// completionTime =0;
// }
// }
//
// public static void main(String[] args) {
// Scanner inp = new Scanner(System.in);
// System.out.println("Enter the number of entries you want to enter: ");
// int n = inp.nextInt();
// ArrivalBurst[] arrivalBursts = new ArrivalBurst[n];
// for(int i=0; i<n; i++){
// arrivalBursts[i] = new ArrivalBurst();
// arrivalBursts[i].arrivalTime = inp.nextInt();
// arrivalBursts[i].burstTime = inp.nextInt();
// }
// getAverageTime(arrivalBursts);
// displayOutput(arrivalBursts);
// }
//
// public static void displayOutput(ArrivalBurst[] arrivalBursts){
// System.out.println("AT\tBT\tCT\tTAT\tWT");
// double avgWt=0, avgTat=0;
// for (int i=0; i<arrivalBursts.length; i++){
// System.out.println(arrivalBursts[i].arrivalTime + " \t" + arrivalBursts[i].burstTime + " \t" + arrivalBursts[i].completionTime + " \t" +
// arrivalBursts[i].turnAroundTime + " \t" + arrivalBursts[i].waitingTime);
// avgTat += arrivalBursts[i].turnAroundTime;
// avgWt += arrivalBursts[i].waitingTime;
// }
// System.out.println("Average Waiting time: " + avgWt/arrivalBursts.length + "\nAverage Turnaroud Time: " + avgTat/arrivalBursts.length);
// }
//
// public static void getAverageTime(ArrivalBurst[] arrivalBursts){
// arrivalBursts[0].completionTime = arrivalBursts[0].arrivalTime + arrivalBursts[0].burstTime;
// for(int i=1; i<arrivalBursts.length; i++){
// if(arrivalBursts[i].arrivalTime < arrivalBursts[i-1].completionTime)
// arrivalBursts[i].completionTime = arrivalBursts[i-1].completionTime + arrivalBursts[i].burstTime;
// else
// arrivalBursts[i].completionTime = arrivalBursts[i].arrivalTime + arrivalBursts[i].burstTime;
// }
// getAvgWaitingTime(arrivalBursts);
// getAvgTurnaroundTime(arrivalBursts);
// }
//
// public static void getAvgWaitingTime(ArrivalBurst[] arrivalBursts){
// arrivalBursts[0].waitingTime = 0;
// for (int i=1; i<arrivalBursts.length; i++){
// arrivalBursts[i].waitingTime = arrivalBursts[i-1].completionTime - arrivalBursts[i].arrivalTime;
// }
// }
//
// public static void getAvgTurnaroundTime(ArrivalBurst[] arrivalBursts){
// for(int i=0; i<arrivalBursts.length; i++){
// arrivalBursts[i].turnAroundTime = arrivalBursts[i].completionTime - arrivalBursts[i].arrivalTime;
// }
// }
}
|
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": []
}
|
IN-CORRECT
|
cpp
|
/* Code by Saborit */
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC optimize("Ofast")
#define MX 200005
#define INF (1<<30)
#define EPS 1e-9
#define MOD 1000000007
#define mid (x+xend)/2
#define izq nod*2
#define der nod*2+1
#define fr first
#define sc second
#define pb push_back
#define mp make_pair
#define all(X) (X).begin(), (X).end()
#define unique(X) (X).resize(unique(all(X)) - (X).begin())
#ifdef LOCAL
#include "debug.h"
#endif
using namespace std;
using namespace __gnu_pbds;
typedef long long int64;
typedef unsigned long long unt64;
struct pt{
int x, v, id;
bool operator < (const pt& p)const{
return x < p.x;
}
};
int N, n, m;
int A[MX], B[MX];
pt P[MX];
vector<int> values;
int64 sol;
struct segment_tree{
pair<int64, int> T[4*MX];
pair<int64, int> update(int a, int64 b, int x=1, int xend=m, int nod=1){
if( a<=x && xend<=a )
return T[nod] = {T[nod].fr + b, T[nod].sc + 1};
if( a < x || xend < a )
return T[nod];
auto aa = update(a, b, x, mid, izq);
auto bb = update(a, b, mid+1, xend, der);
return T[nod] = {aa.fr + bb.fr, aa.sc + bb.sc};
}
pair<int64, int> query(int a, int b, int x=1, int xend=m, int nod=1){
if( a<=x && xend<=b )
return T[nod];
if( b < x || xend < a )
return {0ll, 0};
auto aa = query(a, b, x, mid, izq);
auto bb = query(a, b, mid+1, xend, der);
return {aa.fr + bb.fr, aa.sc + bb.sc};
}
};
int main(void){
//~ freopen("a.in", "r", stdin);
//~ freopen("a.out", "w", stdout);
scanf("%d", &N);
for(int i=1; i<=N; i++){
scanf("%d", &A[i]);
values.pb(A[i]);
}
sort(all(values));
unique(values);
n = values.size();
for(int i=1; i<=N; i++)
P[i].x = lower_bound(all(values), A[i]) - values.begin() + 1;
values.clear();
for(int i=1; i<=N; i++){
scanf("%d", &B[i]);
values.pb(B[i]);
}
sort(all(values));
unique(values);
m = values.size();
for(int i=1; i<=N; i++)
P[i].v = lower_bound(all(values), B[i]) - values.begin() + 1;
for(int i=1; i<=N; i++)
P[i].id = i;
sort(P+1, P+N+1);
segment_tree ST;
//~ db() << n << " " << m;
for(int i=N; i > 0; i--){
auto q = ST.query(P[i].v, m);
//~ db() << imie(i) << " " << q.fr << " " << q.sc;
sol += q.fr - A[ P[i].id ] * q.sc;
ST.update(P[i].v, A[ P[i].id ]);
}
printf("%lld\n", sol);
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T, class U>
using Pa = pair<T, U>;
template <class T>
using vec = vector<T>;
template <class T>
using vvec = vector<vec<T>>;
template <typename Monoid, typename F>
class SegmentTree {
private:
int sz;
vector<Monoid> seg;
const F op;
const Monoid e;
public:
SegmentTree(int n, const F op, const Monoid &e) : op(op), e(e) {
sz = 1;
while (sz <= n) sz <<= 1;
seg.assign(2 * sz, e);
}
void set(int k, const Monoid &x) { seg[k + sz] = x; }
void build() {
for (int i = sz - 1; i > 0; i--) {
seg[i] = op(seg[2 * i], seg[2 * i + 1]);
}
}
void update(int k, const Monoid &x) {
k += sz;
seg[k] = x;
while (k >>= 1) {
seg[k] = op(seg[2 * k], seg[2 * k + 1]);
}
}
Monoid query(int l, int r) {
Monoid L = e, R = e;
for (l += sz, r += sz; l < r; l >>= 1, r >>= 1) {
if (l & 1) L = op(L, seg[l++]);
if (r & 1) R = op(seg[--r], R);
}
return op(L, R);
}
Monoid operator[](const int &k) const { return seg[k + sz]; }
};
template <class T>
class Compress {
map<T, int> idx;
map<int, T> value;
vector<T> cmp;
public:
int N;
Compress(vector<T> v) {
for (auto &x : v) cmp.push_back(x);
sort(cmp.begin(), cmp.end());
cmp.erase(unique(cmp.begin(), cmp.end()), cmp.end());
N = cmp.size();
for (int i = 0; i < N; i++) idx[cmp[i]] = i;
}
int id(T val) { return idx[val]; }
T val(int id) { return cmp[id]; }
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N;
cin >> N;
vec<ll> X(N), V(N);
for (int i = 0; i < N; i++) cin >> X[i];
for (int i = 0; i < N; i++) cin >> V[i];
Compress<ll> cmp(X);
vec<ll> P(N + 1), M(N + 1), Z(N + 1);
vec<ll> PC(N + 1), MC(N + 1), ZC(N + 1);
for (int i = 0; i < N; i++) {
if (V[i] > 0) {
P[cmp.id(X[i])] += X[i];
PC[cmp.id(X[i])]++;
} else if (V[i] < 0) {
M[cmp.id(X[i]) + 1] += X[i];
MC[cmp.id(X[i]) + 1]++;
} else {
Z[cmp.id(X[i]) + 1] += X[i];
ZC[cmp.id(X[i]) + 1]++;
}
}
for (int i = 0; i < N; i++) {
M[i + 1] += M[i];
MC[i + 1] += MC[i];
Z[i + 1] += Z[i];
ZC[i + 1] += ZC[i];
}
for (int i = N - 1; i >= 0; i--) {
P[i] += P[i + 1];
PC[i] += PC[i + 1];
}
struct state {
ll sum, cnt;
};
auto op = [](state L, state R) {
return (state){L.sum + R.sum, L.cnt + R.cnt};
};
SegmentTree<state, decltype(op)> seg(N, op, (state){0, 0});
vec<int> idx(N);
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&](int i, int j) {
return (V[i] != V[j] ? V[i] > V[j] : X[i] > X[j]);
});
ll ans = 0;
for (int i = 0; i < N; i++) {
int id = idx[i];
if (V[id] <= 0) break;
int xid = cmp.id(X[id]);
ans += MC[xid] * X[id] - M[xid];
state res = seg.query(xid, N);
ans += res.sum - X[id] * res.cnt;
seg.update(xid, {X[id], 1});
}
sort(idx.begin(), idx.end(), [&](int i, int j) {
return (V[i] != V[j] ? V[i] < V[j] : X[i] < X[j]);
});
for (int i = 0; i < N; i++) seg.set(i, {0, 0});
seg.build();
for (int i = 0; i < N; i++) {
int id = idx[i];
if (V[id] >= 0) continue;
int xid = cmp.id(X[id]);
state res = seg.query(0, xid);
ans += X[id] * res.cnt - res.sum;
seg.update(xid, {X[id], 1});
}
for (int i = 0; i < N; i++)
if (V[i] == 0) {
int xid = cmp.id(X[i]);
ans += MC[xid] * X[i] - M[xid];
ans += P[xid] - PC[xid] * X[i];
ans += MC[xid] * X[i] - Z[xid];
}
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const long long mx = 2 * 1e5 + 5;
const long long mod = 1e9 + 7;
pair<long long, long long> arr[mx * 4];
void update(int node, int left, int right, int pos, int val) {
if (left == right) {
arr[node].first++;
arr[node].second += val;
return;
}
int mid = (left + right) / 2;
if (pos <= mid) {
update(node * 2, left, mid, pos, val);
} else {
update(node * 2 + 1, mid + 1, right, pos, val);
}
arr[node].first = arr[node * 2].first + arr[node * 2 + 1].first;
arr[node].second = arr[node * 2].second + arr[node * 2 + 1].second;
return;
}
pair<long, long> sum(pair<long long, long long> a,
pair<long long, long long> b) {
return {a.first + b.first, a.second + b.second};
}
pair<long long, long long> query(int node, int left, int right, int l, int r) {
if (right < l || left > r) {
return {0, 0};
}
if (right <= r && left >= l) {
return {arr[node].first, arr[node].second};
}
int mid = (left + right) / 2;
return sum(query(node * 2, left, mid, l, r),
query(node * 2 + 1, mid + 1, right, l, r));
}
int main() {
int n;
cin >> n;
pair<int, int> 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 = 0;
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++) {
int myv = p[i].second;
int myx = p[i].first;
pair<int, int> cnt = query(1, 0, n, 0, myv);
ans += (1LL * myx * cnt.first);
ans -= cnt.second;
update(1, 0, n, myv, myx);
}
update(1, 0, n, 0, 5);
pair<int, int> cnt = query(1, 0, n - 1, 0, 0);
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
#include <fstream>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
typedef long long ll;
typedef long double ld;
using namespace std;
using namespace __gnu_pbds;
#define endl "\n"
#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
const int N=2e5+5, mxN=(1<<20)+5;
int mod=998244353 ;
ll mul(ll a, ll b)
{
a%=mod;
b%=mod;
return (a*b)%mod;
}
ll add(ll a, ll b)
{
a%=mod;
b%=mod;
return (a+b+mod)%mod;
}
ll fastpow(ll b, ll p)
{
if(p==0)
return 1;
ll ans=fastpow(b,p/2);
ans=mul(ans,ans);
if(p%2)
ans=mul(ans,b);
return ans;
}
ll fac(ll n)
{
ll ans=1;
while(n)
{
ans=mul(ans,n--);
}
return ans;
}
ll ncr(ll n, ll r)
{
ll ans=fac(n);
ll m=mul(fac(r),fac(n-r));
ans=mul(ans,fastpow(m,mod-2));
return ans;
}
ll co[N];
pair<int, int>arr[N];
multiset<int>st1,st2;
int n;
int main()
{
FIO
cin>>n;
for(int i=0; i<n; i++)
cin>>arr[i].first;
for(int i=0; i<n; i++)
cin>>arr[i].second;
sort(arr,arr+n);
for(int i=0; i<n; i++)
{
if(arr[i].second>0)
{
co[i]+=st2.size();
co[i] +=distance(st1.begin(),st1.upper_bound(arr[i].second));
st1.insert(arr[i].second);
}
else if(arr[i].second<0)
{
int val=-arr[i].second;
co[i]+=( st2.size()-distance(st2.begin(),st2.lower_bound(arr[i].second)));
st2.insert(val);
}
else
{
co[i]+=st2.size();
st1.insert(0);
}
}
st1.clear();
st2.clear();
for(int i=n-1; i>=0; i--)
{
if(arr[i].second>0)
{
co[i]-=( st1.size()-distance(st1.begin(),st1.lower_bound(arr[i].second)));
st1.insert(arr[i].second);
}
else if(arr[i].second<0)
{
int val=-arr[i].second;
co[i]-=st1.size();
co[i]-=distance(st2.begin(),st2.upper_bound(val));
st2.insert(val);
}
else
{
co[i]-=st1.size();
st2.insert(0);
}
}
ll ans=0;
for(int i=0; i<n; i++)
ans+=co[i]*(ll)arr[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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
template <class Ch, class Tr, class Container>
basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os,
Container const& x) {
os << "{ ";
for (auto& y : x) os << y << " ";
return os << "}";
}
template <class X, class Y>
ostream& operator<<(ostream& os, pair<X, Y> const& p) {
return os << "[ " << p.first << ", " << p.second << "]";
}
typedef struct {
long long pos, v;
} Point;
long long P[200005], V[200005], sum = 0, maxNeg = 0;
long long l = 0, r = 100000000;
int n;
vector<Point> v;
set<long long> usados;
map<long long, long long> DondeEsta;
bool sort_vel(Point a, Point b) {
if (a.v == b.v) return a.pos > b.pos;
return a.v > b.v;
}
bool sort_pos(Point a, Point b) { return a.pos < b.pos; }
long long ft[200005];
long long ft2[200005];
void upd(int i0, long long v) {
for (int i = i0 + 1; i <= 200005; i += i & -i) ft[i] += v;
}
long long get(int i0) {
long long r = 0;
for (int i = i0; i; i -= i & -i) r += ft[i];
return r;
}
int get_sum(int i0, int i1) { return get(i1) - get(i0); }
void upd2(int i0, long long v) {
for (int i = i0 + 1; i <= 200005; i += i & -i) ft2[i] += v;
}
long long get2(int i0) {
long long r = 0;
for (int i = i0; i; i -= i & -i) r += ft2[i];
return r;
}
int get_sum2(int i0, int i1) { return get2(i1) - get2(i0); }
int main() {
cin >> n;
for (int i = 0; i < (n); i++) cin >> P[i];
for (int i = 0; i < (n); i++) {
cin >> V[i];
v.push_back({P[i], V[i]});
}
sort((v.begin()), (v.end()), sort_pos);
for (int i = 0; i < (n); i++) {
upd(i, r - v[i].pos);
upd2(i, 1);
}
for (int i = 0; i < (n); i++) DondeEsta[v[i].pos] = i;
sort((v.begin()), (v.end()), sort_vel);
for (auto x : v) {
long long i = DondeEsta[x.pos];
sum += get_sum(0, i) - ((r - x.pos) * get_sum2(0, i));
upd(i, x.pos - r);
upd2(i, -1);
}
cout << sum << 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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct Point {
int x;
int v;
};
vector<Point> points;
int SUM;
void add_pairwise_dist(int start, int end) {
int m, i, j;
if (start == end) return;
m = (start + end) / 2;
add_pairwise_dist(start, m);
add_pairwise_dist(m + 1, end);
vector<int> rcumsum(end - start + 2);
for (i = end; i >= start; i--) {
rcumsum[i - start] = rcumsum[i - start + 1] + points[i].x;
}
j = m + 1;
for (i = start; i <= m; i++) {
while (j <= end && points[i].v > points[j].v) j++;
SUM += rcumsum[j - start] - (points[j].x - points[i].x) * (end - j + 1);
}
vector<Point> temp(end - start + 1);
i = start;
j = m + 1;
for (int k = 0; k < end - start + 1; k++) {
if (i > m) {
temp[k] = points[j++];
} else if (j > end) {
temp[k] = points[i++];
} else if (points[i].v < points[j].v) {
temp[k] = points[i++];
} else {
temp[k] = points[j++];
}
}
for (int k = 0; k < end - start + 1; k++) {
points[start + k] = temp[k];
}
}
int main() {
int n;
cin >> n;
points.resize(n);
for (int i = 0; i < n; i++) cin >> points[i].x;
for (int i = 0; i < n; i++) cin >> points[i].v;
sort(points.begin(), points.end(),
[](const Point &a, Point const &b) { return a.x < b.x; });
add_pairwise_dist(0, n - 1);
cout << SUM << 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": []
}
|
IN-CORRECT
|
java
|
//package psa.minrazdalja;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class minrazdalja {
/**
* Uvozena abstraktna funkcija za klic Paid<L, R>
*/
public static class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
/**?
* glavna funkcija racunanja:
* sprejme list tipa ArrayList<Pair<Integer, Integer>>, potem st vseh elementov in seveda listo vseh elementov.
*
* nato izracunamo maksimalno distance, ki je sestevek vseh distanc med posameznimi elementi, kar lahko storimo, ker je sortirana tabela.
* V drugem delu odstejemo od maksimalnega sestevka distanc, posamezne ki se sekajo v prihodnosti
* ostane nam samo tocni sestevek minimalnih distanc
*/
public static long elele(ArrayList<Pair<Long,Long>> elementi, int s, Long[] x_el) {
long skupek = 0;
HashMap<Long, Integer> pos = new HashMap<Long, Integer>();
for(int i=0; i<s; ++i) {
skupek += x_el[i] * i + (-1 * x_el[i]) * (s - 1 - i);
pos.put(x_el[i], i);
}
for(int i=0; i<s; ++i){
skupek -= elementi.get(i).getRight() * (pos.get(elementi.get(i).getRight()) - i);
}
//2 1 4 3 5
//2 2 2 3 4
return skupek;
}
public static void main(String[] args) throws IOException {
int st_el;
// uporabimo bufferedreader zaradi 1000x vecje hitrosti kot pa skener
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//System.out.println("Vnesi stevilo elementov: ");
st_el = Integer.parseInt(br.readLine());
//System.out.println(st_el);
Long[] x_el = new Long[st_el];
Long[] v_el = new Long[st_el];
//System.out.println("Vnesi elemente: ");
String x = br.readLine();
String[] strs = x.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
x_el[i] = Long.parseLong(strs[i]);
}
//System.out.println("Vnesi tezo elementov: ");
String y = br.readLine();
String[] strs2 = y.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
v_el[i] = Long.parseLong(strs2[i]);
}
br.close();
//pospravimo skupej v par oblike <integer, integer> oz <hitrost, element>
ArrayList<Pair<Long,Long>> listt = new ArrayList<Pair<Long, Long>>(st_el);
for(int i=0; i<st_el; i++) {
Pair<Long, Long> pair = new Pair<Long, Long>(v_el[i],x_el[i]);
listt.add(pair);
}
/*sortiramo listt od najmanjsega do najvecjega
* - sortiramo prvo po hitrostih (to je glavno najbolj vazno)
* - ce je hitrost ista potem pa sortiramo se glede na element
* - O(n log n)
*/
Collections.sort(listt, new Comparator<Pair<Long, Long>>() {
@Override
public int compare(final Pair<Long, Long> o1, final Pair<Long, Long> o2) {
if(o1.getLeft()<o2.getLeft()) {
return -1;
} else if(o1.getLeft() == o2.getLeft()) {
if(o1.getRight() < o2.getRight()){
return -1;
}else{
return 1;
}
} else {
return 1;
}
}
});
//sortiramo se elemente
// O(n log n)
Arrays.sort(x_el);
//izpisemo elemente
System.out.println(elele(listt,st_el,x_el));
}
}
|
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": []
}
|
IN-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 (int i = 0; i < n; i++) {
scanf("%lld", &o[i].second);
}
for (int i = 0; i < n; i++) {
scanf("%lld", &o[i].first);
}
sort(o, o + n);
for (int i = 0; i < n; i++) {
o[i] = {o[i].second, i + 1};
}
sort(o, o + n);
long long ans = 0;
for (int i = 0; i < n; i++) {
int r = o[i].second, idx = o[i].first;
int s = 0, c = 0;
while (0 < r) {
s += ts[r];
c += tc[r];
r -= (r & -r);
}
ans += idx * c - s;
int 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": []
}
|
IN-CORRECT
|
cpp
|
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=2e5,inf=1e9,R=2e8;
struct segment
{
int l,r,cnt;long sm;
}seg[34*N+2];
int sz;
void upd(int node,int lo,int hi,int id,long vl)
{
//cout<<lo<<" "<<hi<<" "<<id<<endl;getchar();
if(lo==hi)
{
seg[node].sm+=vl;seg[node].cnt++;
return ;
}
int md=(lo+hi)/2;
if(id<=md)
{
if(!seg[node].l)seg[node].l=++sz;
upd(seg[node].l,lo,md,id,vl);
}
else
{
if(!seg[node].r)seg[node].r=++sz;
upd(seg[node].r,md+1,hi,id,vl);
}
seg[node].sm=seg[seg[node].l].sm+seg[seg[node].r].sm;
seg[node].cnt=seg[seg[node].l].cnt+seg[seg[node].r].cnt;
}
pair<long,long>get(int node,int lo,int hi,int id)
{
if(hi<=id)return {seg[node].cnt,seg[node].sm};
if(lo>id)return {0,0};int md=(lo+hi)/2;
pair<int,int>p1=get(seg[node].l,lo,md,id);
pair<int,int>p2=get(seg[node].r,md+1,hi,id);
return {p1.first+p2.first,p1.second+p2.second};
}
pair<int,int>pp[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;
for(int i=1;i<=n;i++)cin>>pp[i].first;
for(int i=1;i<=n;i++)cin>>pp[i].second;
sort(pp+1,pp+n+1);long ans=0;
/*for(int i=1;i<=n;i++)
cout<<pp[i].first<<" ";
cout<<endl;
for(int i=1;i<=n;i++)
cout<<pp[i].second<<" ";
cout<<endl;*/
sz=1;
for(int i=1;i<=n;i++)
{
upd(1,0,2*R,pp[i].second+R,pp[i].first);
pair<long,long>p=get(1,0,2*R,pp[i].second+R);
//cout<<p.first<<" ** "<<p.second<<endl;
ans+=pp[i].first*p.first-p.second;
}
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
double movingPt(double x[], double v[], int j) {
double d = 0;
for (int g = 0; g < j - 1; g++) {
for (int h = g + 1; h < j; h++) {
if (v[g] == v[h]) {
d += abs(x[g] - x[h]);
continue;
} else if (x[g] > x[h] and v[h] - v[g] > 0) {
d += 0;
continue;
} else if (x[g] < x[h] and v[g] - v[h] > 0) {
d += 0;
} else {
d += abs(x[g] - x[h]);
}
}
}
return d;
}
int main() {
int j;
cin >> j;
double x[j], v[j];
for (int g = 0; g < j; g++) {
cin >> x[g];
}
for (int g = 0; g < j; g++) {
cin >> v[g];
}
cout << movingPt(x, v, j);
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 2e5 + 5;
int N, mapval[maxn], len;
struct node {
int x, v;
} a[maxn];
bool cmp(node a, node b) { return a.x < b.x; }
long long c[maxn][2];
void update(int x, int k, int val) {
while (x <= N) {
c[x][k] += val;
x += x & -x;
}
}
long long query(int x, int k) {
long long ans = 0;
while (x > 0) {
ans += c[x][k];
x -= (x & -x);
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> N;
for (int i = 1; i <= N; i++) cin >> a[i].x;
for (int i = 1; i <= N; i++) cin >> mapval[++len], a[i].v = mapval[len];
sort(a + 1, a + N + 1, cmp);
sort(mapval + 1, mapval + len + 1);
len = unique(mapval + 1, mapval + len + 1) - mapval - 1;
for (int i = 1; i <= N; i++)
a[i].v = (lower_bound(mapval + 1, mapval + len + 1, a[i].v) - mapval);
long long ans = 0;
for (int i = 1; i <= N; i++) {
int num = query(a[i].v, 0), sum = query(a[i].v, 1);
ans += (a[i].x * num - sum);
update(a[i].v, 0, 1), update(a[i].v, 1, a[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": []
}
|
IN-CORRECT
|
java
|
//make sure to make new file!
import java.io.*;
import java.util.*;
public class F624{
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(f.readLine());
StringTokenizer st1 = new StringTokenizer(f.readLine());
StringTokenizer st2 = new StringTokenizer(f.readLine());
int[] x = new int[n];
int[] v = new int[n];
Pair[] pairs = new Pair[n];
for(int k = 0; k < n; k++){
x[k] = Integer.parseInt(st1.nextToken());
v[k] = Integer.parseInt(st2.nextToken());
pairs[k] = new Pair(x[k],v[k]);
}
Arrays.sort(pairs);
Arrays.sort(x);
long answer = 0L;
HashMap<Integer,Integer> indexof = new HashMap<Integer,Integer>();
for(int k = 0; k < n; k++){
answer += (long)(x[k] * (-n+1+2*k));
indexof.put(x[k],k);
}
for(int k = 0; k < n; k++){
if(k < indexof.get(pairs[k].x)){
//subtract
answer -= (long)(pairs[k].x*(indexof.get(pairs[k].x)-k));
} else if(k > indexof.get(pairs[k].x)){
answer += (long)(pairs[k].x*(k-indexof.get(pairs[k].x)));
}
}
out.println(answer);
out.close();
}
public static class Pair implements Comparable<Pair>{
int x;
int v;
public Pair(int a, int b){
x = a;
v = b;
}
public int compareTo(Pair p){
if(p.v != v){
return v-p.v;
}
return x-p.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": []
}
|
IN-CORRECT
|
cpp
|
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<climits>
#include<cmath>
#include<ctime>
#include<vector>
#include<queue>
#include<stack>
#include<list>
#include<set>
#include<map>
#include<utility>
#include<algorithm>
using namespace std;
#define FOR(i,a,b) for(register int i=(a);i<(b);++i)
#define FORR(i,a,b) for(register int i=(a);i<=(b);++i)
#define ROR(i,a,b) for(register int i=(a);i>=(b);--i)
#define RORR(i,a,b) for(register int i=(a);i>(b);--i)
#define PQ priority_queue
#define VR vector
#define MST(a,b) memset(a,b,sizeof(a))
#define FGETS(s) fgets(s,sizeof(s),stdin)
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define FI first
#define SE second
typedef long long LL;
typedef long long unsigned LLU;
typedef pair<int,int> pii;
const int MAX = 2e5 + 20;
int n,pos[MAX];
struct Node{
int p,v,no;
bool operator < (const Node &b){
return v != b.v ? v < b.v : p < b.p;
}
}node[MAX],v[MAX];
struct ST{ // n-1
LL v[MAX];
LL sum(int x){
LL s = 0;
while(x){
s += v[x]; x -= x&-x;
}
return s;
}
void add(int x, LL val){
while(x<=n){
v[x]+=val; x += x&-x;
}
}
LL operator [] (int idx){
return sum(idx);
}
}s,c;
int main(void){
scanf("%d",&n);
FOR(i,0,n) scanf("%d",&node[i].p);
FOR(i,0,n) scanf("%d",&node[i].v);
sort(node,node+n,[](Node &a, Node &b){
return a.p < b.p;
});
FOR(i,0,n) node[i].no=i;
memcpy(v,node,sizeof(node));
v[0]={0,0,0};
sort(v+1,v+n);
FOR(i,1,n){
pos[v[i].no]=i;
s.add(i,v[i].p);
c.add(i,1);
}
#ifdef DEBUG
FOR(i,0,n) printf(" (%d, %d)",node[i].p,node[i].v); putchar('\n');
FOR(i,0,n) printf(" (%d, %d)",v[i].p,v[i].v); putchar('\n');
#endif
LL ans = 0;
FOR(i,0,n-1){
int j = lower_bound(v+1,v+n,Node{0,node[i].v,0}) - v;
while(j>1 && node[j-1].v==node[j].v) --j;
if(j>=n) continue;
#ifdef DEBUG
FOR(i,1,n) printf(" s[%d]: %lld, c[%d]: %lld\n",i,s[i],i,c[i]);
printf(" for i: %d (v %d), j: %d\n",i,node[i].v,j);
printf(" s[n]:%lld, s[j-1]: %lld, c[j-1]: %lld\n",s[n],s[j-1],c[j-1]);
printf(" ans += %lld\n",s[n]-s[j-1] - (c[n] - c[j-1])*node[i].p);
#endif
ans += s[n]-s[j-1] - (c[n] - c[j-1])*node[i].p;
int t = pos[i+1];
s.add(t,-v[t].p);
c.add(t,-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": []
}
|
IN-CORRECT
|
java
|
import java.util.Scanner;
public class Movingpoints {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n=s.nextInt();
while(n<2||n>200000) {
n=s.nextInt();
}
int [] pt = new int[n];
int [] vl = new int [pt.length];
for (int i=0;i<pt.length;i++) {
int m = s.nextInt();
while(m<1||m>100000000||duplicate(pt,m)==true) {
m=s.nextInt();
}
pt[i]=m;
}
int temp1=0;
int temp2=0;
for(int j=0;j<vl.length;j++) {
int k=s.nextInt();
while(k<-100000000||k>100000000) {
k=s.nextInt();
}
vl[j]=k;
}
long sum=0;
for(int i=0;i<pt.length;i++) {
for(int x=i+1;x<pt.length;x++) {
if(vl[i]<=vl[x]) {
if(pt[i]<pt[x]) {
sum=sum+distance(pt[i],pt[x]);
}
else {
if(vl[x]<=vl[i]) {
sum=sum+distance(pt[i],pt[x]);
}
}
}
}
}
System.out.println(sum);
}
public static boolean duplicate (int [] a , int b) {
int i =0;
boolean t=false;
while(a[i]!=0 && t==false) {
if (a[i]==b) {
t=true;
}
i++;
}
return t;
}
public static int distance(int a ,int b ) {
int d=Math.abs(b-a);
return d;
}
}
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
template <class C>
inline void log_c(const C& c) {}
template <class C>
inline int sz(const C& c) {
return static_cast<int>(c.size());
}
using namespace std;
using pii = pair<int, int>;
using num = int64_t;
using pll = pair<num, num>;
const std::string eol = "\n";
const int max_x = 100000000;
using It = vector<int>::iterator;
int64_t min_distance_sum(It begin, It end, It tmp_begin) {
if (next(begin) == end) return 0;
auto left_count = distance(begin, end) / 2;
It mid = next(begin, left_count);
int64_t ans_left = min_distance_sum(begin, mid, tmp_begin);
int64_t ans_right = min_distance_sum(mid, end, next(tmp_begin, left_count));
int64_t ans_cross = 0;
It it1 = begin;
It it2 = mid;
It tmp = tmp_begin;
int64_t left_sum = 0;
while (it1 != mid && it2 != end) {
if (*it1 < *it2) {
left_sum += *it1;
*tmp++ = *it1++;
} else {
ans_cross += static_cast<int64_t>(*it2) * distance(begin, it1) - left_sum;
*tmp++ = *it2++;
}
}
copy(it1, mid, tmp);
while (it2 != end) {
ans_cross += static_cast<int64_t>(*it2) * left_count - left_sum;
*tmp++ = *it2++;
}
copy(tmp, next(tmp_begin, distance(begin, end)), begin);
return ans_left + ans_right + ans_cross;
}
int main() {
std::ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<pii> data(n);
for (int k = 0; k < (n); ++k) cin >> data[k].second;
for (int k = 0; k < (n); ++k) cin >> data[k].first;
sort(begin(data), end(data));
vector<int> x(n), tmp(n);
for (int k = 0; k < (n); ++k) x[k] = data[k].second;
cout << min_distance_sum(begin(x), end(x), tmp.begin()) << eol;
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 200000;
long long BIT1[200001];
int cnt1[200001];
map<int, int> r, l;
pair<int, int> arr[200001];
int n;
void upd1(int idx, long long val) {
for (; idx <= N; idx = (idx | (idx + 1))) {
BIT1[idx] += val;
cnt1[idx]++;
}
}
pair<long long, int> query1(int idx) {
if (idx < 0) return {0, 0};
long long sum = 0;
int ct = 0;
for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {
sum += BIT1[idx];
ct += cnt1[idx];
}
return {sum, ct};
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) cin >> arr[i].first;
for (int i = 1; i <= n; i++) cin >> arr[i].second;
sort(arr + 1, arr + n + 1);
for (int i = 1; i <= n; i++) r[arr[i].second] = 0;
int ind = 1;
for (auto &it : r) {
it.second = ind;
ind++;
}
long long ans = 0;
for (int i = 1; i <= n; i++) {
int vel = r[arr[i].second];
pair<long long, int> p = query1(vel);
ans += (p.second) * (arr[i].first);
ans -= p.first;
upd1(vel, arr[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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
long long int n;
long long int x[200005];
vector<pair<long long int, long long int> > cord;
map<long long int, long long int> vel_freq, vel_map;
long long int num[3 * 200005], xcnt[3 * 200005];
int get_cnt(long long int node, long long int l, long long int r,
long long int start, long long int end) {
if (start > r || end < l) return 0;
if (start >= l && end <= r) {
return num[node];
}
long long int mid = (start + end) / 2;
long long int left = 0, right = 0;
if (r >= start && r <= mid)
left = get_cnt(2 * node, l, r, start, mid);
else
right = get_cnt(2 * node + 1, l, r, (mid + 1), end);
return left + right;
}
void add_vel(long long int node, long long int start, int end,
long long int idx) {
if (start == end) {
num[node]++;
return;
}
long long int mid = (start + end) / 2;
if (idx >= start && idx <= mid) {
add_vel(2 * node, start, mid, idx);
} else
add_vel(2 * node + 1, mid + 1, end, idx);
num[node] = num[2 * node] + num[2 * node + 1];
}
void add_x(long long int node, long long int start, long long int end,
long long int idx, long long int val) {
if (start == end) {
xcnt[node] += val;
return;
}
long long int mid = (start + end) / 2;
if (idx >= start && idx <= mid)
add_x(2 * node, start, mid, idx, val);
else
add_x(2 * node + 1, mid + 1, end, idx, val);
xcnt[node] = xcnt[2 * node] + xcnt[2 * node + 1];
}
long long int get_x_sum(long long int node, long long int start,
long long int end, long long int l, long long int r) {
if (start > r || end < l) return 0;
if (start >= l && end <= r) {
return xcnt[node];
}
long long int mid = (start + end) / 2, left = 0, right = 0;
if (r >= start && r <= mid)
left = get_x_sum(2 * node, start, (start + end) / 2, l, r);
else
right = get_x_sum(2 * node + 1, (start + end) / 2 + 1, end, l, r);
return left + right;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++) cin >> x[i];
for (int i = 0; i < n; i++) {
long long int cur_vel;
cin >> cur_vel;
cord.push_back({x[i], cur_vel});
vel_freq[cur_vel]++;
}
long long int k = 0;
sort(cord.begin(), cord.end());
for (auto it = vel_freq.begin(); it != vel_freq.end(); it++) {
vel_map[it->first] = k;
k++;
}
long long int ans = 0;
for (int i = 0; i < n; i++) {
long long int cur_cnt =
cord[i].first * (get_cnt(1, 0, vel_map[cord[i].second], 0, k - 1));
long long int sum = get_x_sum(1, 0, k - 1, 0, vel_map[cord[i].second]);
add_vel(1, 0, k - 1, vel_map[cord[i].second]);
add_x(1, 0, k - 1, vel_map[cord[i].second], cord[i].first);
ans += cur_cnt - sum;
}
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": []
}
|
IN-CORRECT
|
python3
|
from math import factorial
from collections import Counter
from heapq import heapify, heappop, heappush
import os
import sys
from io import BytesIO, IOBase
# region fastio
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")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')
from bisect import insort
# ------------------------------
import bisect
def main():
n = N()
arrp = list(RL())
arrv = list(RL())
arr = list(zip(arrp, arrv))
arr.sort()
# print(arr)
po = []
ne = []
zero = []
res = 0
for p, v in arr:
if v<0:
for ni in range(len(ne)-1, -1, -1):
vv, pp = ne[ni]
if vv<=v:
res+=(p-pp)
else:
break
else:
for pi in range(len(po)):
vv, pp= po[pi]
if vv<=v:
res+=(p-pp)
else:
break
smne = sum([k for _, k in ne])
res+=p*len(ne)-smne
if v>0:
insort(po, (v, p))
elif v<=0:
insort(ne, (v, p))
# else:
# zero.append((v, p))
# print(po, ne, res)
print(res)
if __name__ == "__main__":
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": []
}
|
IN-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();
int[] x = new int[n];
int[] v = new int[n];
int 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 += x[i] * (2 * i + 1 - n);
// record position of x[i]
rank.put(x[i], i);
}
for (int i = 0; i < n; ++i) {
ans -= ps[i].first * (rank.get(ps[i].first) - i);
// ans -= 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": []
}
|
IN-CORRECT
|
python3
|
numberofpoints=int(input())
initcoords=input().split(" ")
speeds=input().split(" ")
initcoords=tuple(map(float,initcoords))
speeds=tuple(map(float,speeds))
def twopoints(coords,velos):
firstv=velos[0]
secondv=velos[1]
firstc=coords[0]
secondc=coords[1]
dif=abs(firstc-secondc)
nextdif=abs((firstc+(10**-10)*firstv)-(secondc+(10**-10)*secondv))
if dif>nextdif:
return 0
else:
return dif
lis=[]
for first in range(numberofpoints):
for second in range(first+1,numberofpoints):
tup=(first,second)
lis.append(tup)
sum=0
for tuple in lis:
a=(speeds[tuple[0]],speeds[tuple[1]])
b=(initcoords[tuple[0]],initcoords[tuple[1]])
sum+=twopoints(b,a)
print(int(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": []
}
|
IN-CORRECT
|
java
|
//package psa.minrazdalja;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class minrazdalja {
/**
* Uvozena abstraktna funkcija za klic Paid<L, R>
*/
public static class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
/**?
* glavna funkcija racunanja:
* sprejme list tipa ArrayList<Pair<Integer, Integer>>, potem st vseh elementov in seveda listo vseh elementov.
*
* nato izracunamo maksimalno distance, ki je sestevek vseh distanc med posameznimi elementi, kar lahko storimo, ker je sortirana tabela.
* V drugem delu odstejemo od maksimalnega sestevka distanc, posamezne ki se sekajo v prihodnosti
* ostane nam samo tocni sestevek minimalnih distanc
*/
public static long elele(ArrayList<Pair<Long,Long>> elementi, int s, Long[] x_el) {
long skupek = 0;
HashMap<Long, Integer> pos = new HashMap<Long, Integer>(s);
for(int i=0; i<s; ++i) {
skupek += x_el[i] * i + (-1 * x_el[i]) * (s - 1 - i);
pos.put(x_el[i], i);
}
for(int i=0; i<s; ++i){
skupek -= elementi.get(i).getRight() * ( pos.get(elementi.get(i).getRight()) - i );
}
//2 1 4 3 5
//2 2 2 3 4
return skupek;
}
public static void main(String[] args) throws IOException {
int st_el;
// uporabimo bufferedreader zaradi 1000x vecje hitrosti kot pa skener
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//System.out.println("Vnesi stevilo elementov: ");
st_el = Integer.parseInt(br.readLine());
//System.out.println(st_el);
Long[] x_el = new Long[st_el];
Long[] v_el = new Long[st_el];
//System.out.println("Vnesi elemente: ");
String x = br.readLine();
String[] strs = x.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
x_el[i] = Long.parseLong(strs[i]);
}
//System.out.println("Vnesi tezo elementov: ");
String y = br.readLine();
String[] strs2 = y.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
v_el[i] = Long.parseLong(strs2[i]);
}
br.close();
//pospravimo skupej v par oblike <integer, integer> oz <hitrost, element>
ArrayList<Pair<Long,Long>> listt = new ArrayList<Pair<Long, Long>>(st_el);
for(int i=0; i<st_el; i++) {
Pair<Long, Long> pair = new Pair<Long, Long>(v_el[i],x_el[i]);
listt.add(pair);
}
/*sortiramo listt od najmanjsega do najvecjega
* - sortiramo prvo po hitrostih (to je glavno najbolj vazno)
* - ce je hitrost ista potem pa sortiramo se glede na element
* - O(n log n)
*/
Collections.sort(listt, new Comparator<Pair<Long, Long>>() {
@Override
public int compare(final Pair<Long, Long> o1, final Pair<Long, Long> o2) {
if(o1.getLeft()<o2.getLeft()) {
return -1;
} else if(o1.getLeft() == o2.getLeft()) {
if(o1.getRight() < o2.getRight()){
return -1;
}else{
return 1;
}
} else {
return 1;
}
}
});
//sortiramo se elemente
// O(n log n)
Arrays.sort(x_el);
//izpisemo elemente
System.out.println(elele(listt,st_el,x_el));
}
}
|
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct Point {
int x;
int v;
};
vector<Point> points;
int SUM;
void add_pairwise_dist(int start, int end) {
int m, i, j;
if (start == end) return;
m = (start + end) / 2;
add_pairwise_dist(start, m);
add_pairwise_dist(m + 1, end);
vector<int> rcumsum(end - start + 2);
for (i = end; i >= start; i--) {
rcumsum[i - start] = rcumsum[i - start + 1] + points[i].x;
}
j = m + 1;
for (i = start; i <= m; i++) {
while (j <= end && points[i].v > points[j].v) j++;
if (j > end) break;
SUM += rcumsum[j - start] - points[i].x * (end - j + 1);
}
vector<Point> temp(end - start + 1);
i = start;
j = m + 1;
for (int k = 0; k < end - start + 1; k++) {
if (i > m) {
temp[k] = points[j++];
} else if (j > end) {
temp[k] = points[i++];
} else if (points[i].v < points[j].v) {
temp[k] = points[i++];
} else {
temp[k] = points[j++];
}
}
for (int k = 0; k < end - start + 1; k++) {
points[start + k] = temp[k];
}
}
int main() {
int n;
cin >> n;
points.resize(n);
for (int i = 0; i < n; i++) cin >> points[i].x;
for (int i = 0; i < n; i++) cin >> points[i].v;
sort(points.begin(), points.end(),
[](const Point &a, Point const &b) { return a.x < b.x; });
add_pairwise_dist(0, n - 1);
cout << SUM << 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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end() /* a + all(x) - b */
#define makeUnique(vec) std::sort(all(vec)); vec.resize(unique(all(vec)) - vec.begin())
#define in(name, type) type name; std::cin >> name
#define gin(var) std::cin >> var
#define LOG_vec(vec, sep) for (int fl = 0; fl < vec.size(); fl++) { std::cout << vec[fl] << sep; } std::cout << "\n"
#define LOG(x, sep) std::cout << x << sep
#define LOG(x) std::cout << x << "\n";
#define ll long long
int iin() { in(r, int); return r; }
struct Random {
int lower, upper;
Random() : lower(0), upper(10) { }
Random(int l, int u) : lower(0), upper(10) { lower = l; upper = u; }
void set(int l, int u) { lower = l; upper = u; }
int get() { return rand() % upper + lower; }
} random;
int getRand() { return random.get(); }
void compile();
const bool isT = false;
#define imp LOG(NULL)
int main() {
if (isT) {
in(t, int);
for (int i = 0; i < t; i++) { compile(); }
return 0;
}
compile();
return 0;
}
class Solution {
public:
void run() {
input();
std::sort(all(x));
std::sort(all(p));
int r = 0;
std::map <int, int> m;
for (int i = 0; i < n; i++) { r += x[i] * (2 * i + 1 - n); m[x[i]] = i; }
for (int i = 0; i < n; i++) { r -= p[i].x * (m[p[i].x] - i); }
LOG(r);
}
private:
struct Point {
int x, v;
Point(int X, int V) { x = X; v = V; }
bool operator<(const Point& a) const { if (v == a.v) { return x < a.x; } return v < a.v; }
};
int n;
std::vector <int> x, v;
std::vector <Point> p;
void input() {
gin(n);
x.resize(n); v.resize(n);
std::generate(all(x), iin);
std::generate(all(v), iin);
for (int i = 0; i < n; i++) { Point cp(x[i], v[i]); p.push_back(cp); }
}
};
void compile() { Solution sol; sol.run(); }
|
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": []
}
|
IN-CORRECT
|
python3
|
from math import factorial
from collections import Counter
from heapq import heapify, heappop, heappush
import os
import sys
from io import BytesIO, IOBase
# region fastio
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")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')
from bisect import insort
# ------------------------------
import bisect
def main():
n = N()
arrp = list(RL())
arrv = list(RL())
arr = list(zip(arrp, arrv))
arr.sort()
# print(arr)
po = []
ne = []
res = 0
for p, v in arr:
if v<0:
# print(p, v, ne)
for ni in range(len(ne)-1, -1, -1):
vv, pp = ne[ni]
if vv<v:
res+=(p-pp)
else:
break
else:
for pi in range(len(po)):
vv, pp= po[pi]
if vv<=v:
res+=(p-pp)
else:
break
smne = sum([k for _, k in ne])
res+=p*len(ne)-smne
if v>0:
insort(po, (v, p))
elif v<=0:
insort(ne, (v, p))
# else:
# zero.append((v, p))
# print(po, ne, res)
print(res)
if __name__ == "__main__":
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": []
}
|
IN-CORRECT
|
java
|
//package psa.minrazdalja;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class minrazdalja {
/**
* Uvozena abstraktna funkcija za klic Paid<L, R>
*/
public static class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
/**?
* glavna funkcija racunanja:
* sprejme list tipa ArrayList<Pair<Integer, Integer>>, potem st vseh elementov in seveda listo vseh elementov.
*
* nato izracunamo maksimalno distance, ki je sestevek vseh distanc med posameznimi elementi, kar lahko storimo, ker je sortirana tabela.
* V drugem delu odstejemo od maksimalnega sestevka distanc, posamezne ki se sekajo v prihodnosti
* ostane nam samo tocni sestevek minimalnih distanc
*/
public static long elele(ArrayList<Pair<Long,Long>> elementi, int s, Long[] x_el) {
long skupek = 0;
HashMap<Long, Long> pos = new HashMap<Long, Long>(s);
for(int i=0; i<s; ++i) {
skupek += x_el[i] * i + (-1 * x_el[i]) * (s - 1 - i);
pos.put(x_el[i], (long)i);
}
for(int i=0; i<s; ++i){
skupek -= elementi.get(i).getRight() * ( pos.get(elementi.get(i).getRight()) - (long)i );
}
//2 1 4 3 5
//2 2 2 3 4
return skupek;
}
public static void main(String[] args) throws IOException {
int st_el;
// uporabimo bufferedreader zaradi 1000x vecje hitrosti kot pa skener
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//System.out.println("Vnesi stevilo elementov: ");
st_el = Integer.parseInt(br.readLine());
//System.out.println(st_el);
Long[] x_el = new Long[st_el];
Long[] v_el = new Long[st_el];
//System.out.println("Vnesi elemente: ");
String x = br.readLine();
String[] strs = x.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
x_el[i] = Long.parseLong(strs[i]);
}
//System.out.println("Vnesi tezo elementov: ");
String y = br.readLine();
String[] strs2 = y.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
v_el[i] = Long.parseLong(strs2[i]);
}
br.close();
//pospravimo skupej v par oblike <integer, integer> oz <hitrost, element>
ArrayList<Pair<Long,Long>> listt = new ArrayList<Pair<Long, Long>>(st_el);
for(int i=0; i<st_el; i++) {
Pair<Long, Long> pair = new Pair<Long, Long>(v_el[i],x_el[i]);
listt.add(pair);
}
/*sortiramo listt od najmanjsega do najvecjega
* - sortiramo prvo po hitrostih (to je glavno najbolj vazno)
* - ce je hitrost ista potem pa sortiramo se glede na element
* - O(n log n)
*/
Collections.sort(listt, new Comparator<Pair<Long, Long>>() {
@Override
public int compare(final Pair<Long, Long> o1, final Pair<Long, Long> o2) {
if(o1.getLeft()<o2.getLeft()) {
return -1;
} else if(o1.getLeft() == o2.getLeft()) {
if(o1.getRight() < o2.getRight()){
return -1;
}else{
return 1;
}
} else {
return 1;
}
}
});
//sortiramo se elemente
// O(n log n)
Arrays.sort(x_el);
//izpisemo elemente
System.out.println(elele(listt,st_el,x_el));
}
}
|
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": []
}
|
IN-CORRECT
|
java
|
import java.io.*;
import java.util.*;
public class Main {
static FastScanner in = new FastScanner();
public static void main(String[] args) throws IOException {
int n = in.nextInt();
point[] a = new point[n];
for (int i = 0; i < n; i++) {
a[i] = new point(in.nextInt(), 0);
}
int ans = 0;
for (int i = 0; i < n; i++) {
a[i].v = in.nextInt();
}
Arrays.sort(a, new point());
point[] b = new point[n];
for (int i = 0; i < n; ) {
int j = i;
while (i < n && a[i].v == a[j].v) {
b[i] = new point(a[i].x, j);
i++;
}
}
Arrays.sort(b, new point1());
segment_tree st = new segment_tree(n, new int[n]);
for (int i = 0; i < n; i++) {
ans += st.get(1, 0, n - 1, 0, b[i].v) - st.get_cnt(1, 0, n - 1, 0, b[i].v) * b[i].x;
st.set(1, 0, n - 1, b[i].v, b[i].x);
}
in.out.println(-ans);
in.out.close();
}
}
class point implements Comparator<point> {
int x, v;
public point(int x, int v) {
this.x = x;
this.v = v;
}
public point() {
}
@Override
public int compare(point o1, point o2) {
return Integer.compare(o1.v, o2.v);
}
}
class point1 implements Comparator<point> {
@Override
public int compare(point o1, point o2) {
return Integer.compare(o1.x, o2.x);
}
}
class segment_tree {
int n;
int[] a;
long[] sum;
int[] cnt;
public segment_tree(int n, int[] a) {
this.n = n;
this.a = a;
sum = new long[n * 4];
cnt = new int[n * 4];
}
void set(int v, int tl, int tr, int ind, int val) {
if (tl > ind || tr < ind) return;
if (tl == tr) {
sum[v] += val;
cnt[v]++;
return;
}
int tm = (tl + tr) >> 1;
set((v << 1), tl, tm, ind, val);
set((v << 1) | 1, tm + 1, tr, ind, val);
sum[v] = sum[v << 1] + sum[(v << 1) | 1];
cnt[v] = cnt[v << 1] + cnt[(v << 1) | 1];
}
long get(int v, int tl, int tr, int l, int r) {
if (r < tl || l > tr) return 0;
if (l <= tl && tr <= r) {
return sum[v];
}
int tm = (tl + tr) >> 1;
return get(v << 1, tl, tm, l, r) + get((v << 1) | 1, tm + 1, tr, l, r);
}
long get_cnt(int v, int tl, int tr, int l, int r) {
if (r < tl || l > tr) return 0;
if (l <= tl && tr <= r) {
return cnt[v];
}
int tm = (tl + tr) >> 1;
return get_cnt(v << 1, tl, tm, l, r) + get_cnt((v << 1) | 1, tm + 1, tr, l, r);
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
PrintWriter out;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
FastScanner(String in, String out_) throws FileNotFoundException {
br = new BufferedReader(new FileReader(in));
out = new PrintWriter(out_);
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
long long R = 7 + 1e9, NUMTESTCASE;
const int NN = 10 + 9e5;
const double pi = acos(-1.0);
int di[4] = {1, 0, -1, 0}, dj[4] = {0, 1, 0, -1},
DI[8] = {1, 1, 0, -1, -1, -1, 0, 1}, DJ[8] = {0, 1, 1, 1, 0, -1, -1, -1};
using namespace std;
long long n, Draft[NN], Coor[NN], Speed[NN], Ans, Flag, Lazy[NN], Max[NN],
Min[NN];
pair<long long, long long> Status[NN], Tree[NN];
map<long long, long long> Draft2;
vector<pair<pair<long long, long long>, long long>> Calc;
map<long long, set<long long, greater<long long>>> CommSpeed;
void Build(int Node = 1, int st = 1, int en = n) {
if (st == en) {
Min[Node] = Max[Node] = Speed[st];
Tree[Node] = Status[Node];
return;
}
Build(2 * Node, st, (st + en) / 2);
Build(2 * Node + 1, (st + en) / 2 + 1, en);
Max[Node] = max(Max[2 * Node], Max[2 * Node + 1]);
Min[Node] = min(Min[2 * Node], Min[2 * Node + 1]);
}
void Solve(int End, int Spinit, int Node = 1, int st = 1, int en = n) {
if (st > End) return;
if (Min[Node] - Spinit >= 0) return;
if (Max[Node] - Spinit < 0) return void(Calc.push_back({{st, en}, End + 1}));
Solve(End, Spinit, 2 * Node, st, (st + en) / 2);
Solve(End, Spinit, 2 * Node + 1, (st + en) / 2 + 1, en);
}
int main() {
cin >> n;
for (int i = (1); i <= (n); ++i) scanf("%I64d", &Draft[i]);
for (int i = (1); i <= (n); ++i) {
scanf("%I64d", &Flag);
Draft2[Draft[i]] = Flag;
CommSpeed[Flag].insert(Draft[i]);
}
n &= 0;
for (auto Itter : Draft2) {
n++;
Coor[n] = Itter.first;
Speed[n] = Itter.second;
Status[n] = {Itter.first, Itter.second};
}
for (auto Itter : CommSpeed) {
Flag = 0;
while (Itter.second.size()) {
Ans +=
*Itter.second.begin() * (long long)(Itter.second.size() - 1 - Flag);
Flag++;
Itter.second.erase(Itter.second.begin());
}
}
Build();
for (int i = (2); i <= (n); ++i) Solve(i - 1, Speed[i]);
memset(Draft, 0, sizeof(Draft));
for (auto u : Calc) {
Ans += u.second * (u.first.second - u.first.first + 1);
Draft[u.first.first]++;
Draft[u.first.second + 1]--;
}
for (int i = (1); i <= (n); ++i) Draft[i] += Draft[i - 1];
for (int i = (1); i <= (n); ++i) Ans -= Draft[i] * Coor[i];
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": []
}
|
IN-CORRECT
|
python2
|
import sys
from collections import defaultdict
range = xrange
input = raw_input
class segtree:
def __init__(self, n):
m = 1
while m < n: m *= 2
self.m = m
self.data1 = [0.0]*(m + m)
self.data2 = [0]*(m + m)
def add(self, i, val):
i += self.m
while i:
self.data1[i] += val
self.data2[i] += 1
i >>= 1
def summer(self, l, r):
l += self.m
r += self.m
s1 = 0.0
s2 = 0
while l < r:
if l & 1:
s1 += self.data1[l]
s2 += self.data2[l]
l += 1
if r & 1:
r -= 1
s1 += self.data1[r]
s2 += self.data2[r]
l >>= 1
r >>= 1
return s1,s2
jj = -1
def map_fun():
global jj
jj += 1
return jj
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
X = inp[ii: ii + n]; ii += n
V = inp[ii: ii + n]; ii += n
order = sorted(range(n), key = lambda i: (V[i], X[i]))
mapper = defaultdict(map_fun)
for x in sorted(X):
mapper[x]
seg = segtree(len(mapper))
total = 0
for i in order:
x = X[i]
j = mapper[x]
s1, s2 = seg.summer(0,j)
total += s2 * x - s1
seg.add(j, x)
print int(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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
vector<long> inverse(vector<long>& perm) {
long n = perm.size();
vector<long> ret(n);
for (long i = 0; i < n; ++i) {
ret[perm[i]] = i;
}
return ret;
}
vector<long> assignPermutation(const vector<long>& uniqs) {
long n = uniqs.size();
vector<pair<long, long>> withIndices(n);
for (long i = 0; i < n; ++i) {
withIndices[i] = {uniqs[i], i};
}
sort(withIndices.begin(), withIndices.end());
vector<long> temp(n);
for (long i = 0; i < n; ++i) {
temp[i] = withIndices[i].second;
}
return inverse(temp);
}
int main() {
long n;
cin >> n;
cin.ignore();
vector<long> x(n);
vector<long> v(n);
vector<pair<long, long>> data(n);
for (long i = 0; i < n; ++i) {
cin >> x[i];
}
cin.ignore();
for (long i = 0; i < n; ++i) {
cin >> v[i];
data[i] = {v[i], x[i]};
}
cin.ignore();
sort(data.begin(), data.end());
vector<long> xtemp(n);
for (long i = 0; i < n; ++i) xtemp[i] = data[i].second;
auto xranks = assignPermutation(xtemp);
sort(x.begin(), x.end());
long totsum = 0;
for (long i = 0; i < n; ++i) {
totsum += (i * x[i]);
totsum -= (n - 1 - i) * x[i];
}
for (long i = 0; i < n; ++i) {
long netleftjumps = i - xranks[i];
totsum += (netleftjumps)*xtemp[i];
}
cout << totsum << 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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
pair<int, int> d[200000 + 10];
int vs[200000 + 10];
int n;
pair<int, long long> add_(pair<int, long long> a, pair<int, long long> b) {
return {a.first + b.first, a.second + b.second};
}
pair<int, long long int> init(vector<pair<int, long long>> &a,
vector<pair<int, long long>> &tree, int node,
int start, int end) {
if (start == end) {
return tree[node] = a[start];
} else {
return tree[node] =
add_(init(a, tree, node * 2, start, (start + end) / 2),
init(a, tree, node * 2 + 1, (start + end) / 2 + 1, end));
}
}
void update(vector<pair<int, long long>> &tree, int node, int start, int end,
int index, long long diff) {
if (index < start || index > end) return;
tree[node].first++;
tree[node].second += diff;
if (start != end) {
update(tree, node * 2, start, (start + end) / 2, index, diff);
update(tree, node * 2 + 1, (start + end) / 2 + 1, end, index, diff);
}
}
pair<int, long long> sum(vector<pair<int, long long>> &tree, int node,
int start, int end, int left, int right) {
if (left > end || right < start) {
return {0, 0};
}
if (left <= start && end <= right) {
return tree[node];
}
return add_(sum(tree, node * 2, start, (start + end) / 2, left, right),
sum(tree, node * 2 + 1, (start + end) / 2 + 1, end, left, right));
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &d[i].first);
for (int i = 0; i < n; i++) {
scanf("%d", &d[i].second);
vs[i] = d[i].second;
}
sort(vs, vs + n);
for (int i = 0; i < n; i++) {
d[i].second = lower_bound(vs, vs + n, d[i].second) - vs;
}
sort(d, d + n);
int h = (int)ceil(log2(n));
int tree_size = (1 << (h + 1));
vector<pair<int, long long>> tree(tree_size);
vector<pair<int, long long>> a(tree_size);
init(a, tree, 1, 0, n - 1);
long long res = 0;
for (int i = 0; i < n; i++) {
auto sum_d = sum(tree, 1, 0, n - 1, 0, d[i].second);
res += d[i].first * sum_d.first;
res -= sum_d.second;
update(tree, 1, 0, n - 1, d[i].second, d[i].first);
}
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": []
}
|
IN-CORRECT
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 45;
const int lim = 1e8 + 3;
long long n;
pair<long long, long long> a[N];
long long drvo[15 * N], br[15 * N];
int ls[15 * N], rs[15 * N], tsz = 1, root = 1;
void update(int i, int j, int pos, int val, int &node) {
if (!node) {
node = ++tsz;
}
if (i == j) {
drvo[node] += val;
br[node]++;
return;
}
int mid = i + (j - i) / 2;
if (pos <= mid) {
update(i, mid, pos, val, ls[node]);
} else {
update(mid + 1, j, pos, val, rs[node]);
}
drvo[node] = drvo[ls[node]] + drvo[rs[node]];
br[node] = br[ls[node]] + br[rs[node]];
}
long long getsum(int i, int j, int l, int r, int node) {
if (!node || j < l || i > r) {
return 0;
}
if (l <= i && r >= j) {
return drvo[node];
}
int mid = i + (j - i) / 2;
return getsum(i, mid, l, r, ls[node]) + getsum(mid + 1, j, l, r, rs[node]);
}
long long getcnt(int i, int j, int l, int r, int node) {
if (!node || j < l || i > r) {
return 0;
}
if (l <= i && r >= j) {
return br[node];
}
int mid = i + (j - i) / 2;
return getcnt(i, mid, l, r, ls[node]) + getcnt(mid + 1, j, l, r, rs[node]);
}
int main() {
ios_base::sync_with_stdio(false);
cin.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);
long long sol = 0;
for (int i = n; i >= 1; i--) {
if (a[i].second < 0) {
continue;
}
long long s = getsum(0, lim, a[i].second, lim, root),
cnt = getcnt(0, lim, a[i].second, lim, root);
sol += s - cnt * a[i].first;
update(0, lim, a[i].second, a[i].first, root);
}
for (int i = 0; i < 15 * N; i++) {
br[i] = drvo[i] = ls[i] = rs[i] = 0;
tsz = 1;
}
for (long long i = n; i >= 1; i--) {
if (a[i].second >= 0) {
continue;
}
long long s = getsum(0, lim, -a[i].second, lim, root),
cnt = getcnt(0, lim, -a[i].second, lim, root);
sol += s - cnt * a[i].first;
update(0, lim, -a[i].second, a[i].first, root);
}
long long sum = 0, cnt = 0;
for (long long i = n; i >= 1; i--) {
if (a[i].second >= 0) {
cnt++;
sum += a[i].first;
} else {
sol += sum - cnt * a[i].first;
}
}
cout << sol << 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": []
}
|
IN-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];
int P = 1000000007 - 2;
int factorial[10000001] = {0};
int powerFunction(int x, int y) {
int res = 1;
int 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(int maxLimit) {
memset(prime, true, sizeof(prime));
prime[0] = prime[1] = false;
for (int i = 2; maxLimit >= i; i++) {
if (prime[i]) {
for (int j = 2 * i; maxLimit >= j; j += i) prime[j] = false;
}
}
}
void factorialFunction(int maxLimit) {
factorial[0] = 1;
for (int i = 1; i <= maxLimit; i++)
factorial[i] = (factorial[i - 1] * i) % 1000000007;
return;
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
vector<pair<int, int>> tree[800001];
vector<int> treesum[800001];
vector<pair<int, int>> v;
void build(int node, int start, int end) {
if (start == end) {
vector<pair<int, int>> temp;
temp.push_back({v[start].second, v[start].first});
tree[node] = temp;
vector<int> sum;
int s = 0;
for (int i = 0; tree[node].size() > i; i++) {
s += tree[node][i].second;
treesum[node].push_back(s);
}
return;
}
int mid = (start + end) / 2;
build(2 * node, start, mid);
build(2 * node + 1, mid + 1, end);
int 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 (int k = i; k < tree[2 * node].size(); k++)
tree[node].push_back(tree[2 * node][k]);
for (int k = j; k < tree[2 * node + 1].size(); k++)
tree[node].push_back(tree[2 * node + 1][k]);
int s = 0;
for (int k = 0; tree[node].size() > k; k++) {
s += tree[node][k].second;
treesum[node].push_back(s);
}
}
int n;
pair<int, int> query(int node, int start, int end, int x) {
if (start > x && end <= n) {
pair<int, int> tem = {v[x].second, INT_MIN};
int id = lower_bound(tree[node].begin(), tree[node].end(), tem) -
tree[node].begin();
if (id) {
return {treesum[node].back() - treesum[node][id - 1],
(int)tree[node].size() - id};
}
return {treesum[node].back(), tree[node].size()};
}
if (end <= x || start > n) {
return {0, 0};
}
int mid = (start + end) / 2;
return {query(2 * node, start, mid, x).first +
query(2 * node + 1, mid + 1, end, x).first,
query(2 * node, start, mid, x).second +
query(2 * node + 1, mid + 1, end, x).second};
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
cin >> n;
int x[n + 1], s[n + 1];
for (int i = 1; n >= i; i++) {
cin >> x[i];
}
for (int i = 1; n >= i; i++) {
cin >> s[i];
}
v.push_back({INT_MIN, INT_MIN});
for (int i = 1; n >= i; i++) {
v.push_back({x[i], s[i]});
}
sort(v.begin(), v.end());
build(1, 1, n);
int ans = 0;
for (int i = 1; n >= i; i++) {
int xx = v[i].first;
pair<int, int> temp = query(1, 1, n, i);
temp.first -= xx * temp.second;
ans += temp.first;
}
cout << ans << "\n";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.