Untitled
unknown
c_cpp
a year ago
2.1 kB
17
Indexable
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int tt, tc;
template <class T> struct fenwick_point {
int n;
vector<T> fenw;
fenwick_point(int _n) : n(_n + 5) { fenw.resize(n); }
void add(int i, T v) {
for (++i; i < n; i += (i & -i)) fenw[i] += v;
}
T query(int i) {
T res = 0;
for (++i; i > 0; i -= (i & -i)) res += fenw[i];
return res;
}
T query_range(int l, int r) {
return query(r) - query(l - 1);
}
};
void solve() {
int n;
cin >> n;
vector<ll> a(n), b(n);
for (ll& u : a) cin >> u;
for (ll& u : b) cin >> u;
vector<ll> all(2 * n + 5);
for (int i = 0; i < n; i++) {
all[i] = a[i];
all[i + n] = b[i];
}
sort(all.begin(), all.end());
all.erase(unique(all.begin(), all.end()), all.end());
vector<int> a1(n), b1(n);
for (int i = 0; i < n; i++) {
a1[i] = lower_bound(all.begin(), all.end(), a[i]) - all.begin();
b1[i] = lower_bound(all.begin(), all.end(), b[i]) - all.begin();
}
int q;
cin >> q;
vector<int> x(q), y(q);
for (int i = 0; i < q; i++) {
cin >> x[i] >> y[i];
x[i]--, y[i]--;
}
vector<int> order(q);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(), [&](int i, int j) {
return make_pair(x[i] / 320, y[i]) < make_pair(x[j] / 320, y[j]);
});
vector<ll> query_ans(q);
ll ans = 0;
fenwick_point<ll> sum(2 * n + 5); // sum b
fenwick_point<ll> cnt(2 * n + 5); // cnt b
int l = -1, r = -1;
auto add_a = [&](int i, ll sign) {
ans += sign * (a[i] * cnt.query_range(0, a1[i] - 1) - sum.query_range(0, a1[i] - 1));
ans += sign * (sum.query_range(a1[i], 2 * n) - a[i] * cnt.query_range(a1[i], 2 * n));
};
auto add_b = [&](int i, ll sign) {
sum.add(b1[i], sign * b[i]);
cnt.add(b1[i], sign);
};
for (int query : order) {
while (r < y[query]) add_b(++r, 1);
while (r > y[query]) add_b(r--, -1);
while (l < x[query]) add_a(++l, 1);
while (l > x[query]) add_a(l--, -1);
query_ans[query] = ans;
}
for (ll u : query_ans) cout << u << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
tt = 1, tc = 1;
// cin >> tt;
while (tt--) {
solve();
tc++;
}
}
Editor is loading...
Leave a Comment