Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define all(x) (x).begin(), (x).end()
- #define itn int
- #define make_unique(x) sort((x).begin(), (x).end()); (x).erase(unique((x).begin(), (x).end()), (x).end())
- using namespace std;
- inline int nxt() {
- int x;
- scanf("%d", &x);
- return x;
- }
- const int N = 111111;
- struct Shit {
- array<int, N> cnt;
- set<pair<int, int>> S;
- long long total;
- Shit() {
- cnt.fill(0);
- total = 0;
- }
- void inc(int x) {
- ++cnt[x];
- if (cnt[x] == 2) {
- add(x);
- }
- }
- void add(int x) {
- pair<int, int> p = {x, x};
- auto it = S.lower_bound(p);
- vector<pair<int, int>> to_erase;
- if (it != S.end() && it->first == x + 1) {
- p.second = it->second;
- to_erase.push_back(*it);
- }
- if (it != S.begin()) {
- --it;
- if (it->second == x - 1) {
- p.first = it->first;
- to_erase.push_back(*it);
- }
- }
- for (const auto& q : to_erase) {
- total -= 1ll * (q.second - q.first + 1) * (q.second - q.first + 2) / 2;
- S.erase(q);
- }
- total += 1ll * (p.second - p.first + 1) * (p.second - p.first + 2) / 2;
- S.insert(p);
- }
- };
- vector<int> ev[2][N];
- void solve() {
- int n = nxt(), k = nxt();
- vector<int> c(n), d(n);
- for (int i = 0; i < n; ++i) {
- c[i] = nxt();
- }
- for (int i = 0; i < n; ++i) {
- d[i] = nxt();
- }
- for (int i = 0; i < N; ++i) {
- ev[0][i].clear();
- ev[1][i].clear();
- }
- for (int i = 0; i < n; ++i) {
- ev[0][c[i]].push_back(i);
- ev[1][d[i]].push_back(i);
- }
- long long ans = 1ll * n * (n + 1) / 2;
- for (int t : {0, 1}) {
- Shit shit;
- for (int i = 0; i < N; ++i) {
- if (i - k - 1 >= 0) {
- for (int x : ev[t][i - k - 1]) {
- shit.inc(x);
- }
- }
- ans += shit.total;
- for (int x : ev[t ^ 1][i]) {
- shit.inc(x);
- }
- ans -= shit.total;
- }
- }
- cout << ans << "\n";
- }
- int main() {
- int t = nxt();
- for (int i = 1; i <= t; ++i) {
- cout << "Case #" << i << ": ";
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement