D - Make Target 2 题解 by en_translator
To conveniently handle the expression , we count those with and , and finally sum them up to find the answer.
Here, we will describe how to count those with . Those with can be counted likewise.
When , . Thus, we may iterate all even numbers within , and for each find the number of with and . Since is equivalent to , for a fixed the integers to be counted are within . The number of such can be represented as , which can be computed in time for each . Hence, those with can be counted in time, where .
Sample code:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int l, r, d, u;
cin >> l >> r >> d >> u;
ll ans = 0;
// |x| > |y|
for (int x = l; x <= r; x++) {
if (x % 2 == 0) {
int D = max(d, -abs(x) + 1);
int U = min(u, abs(x) - 1);
int C = U - D + 1;
ans += max(C, 0);
}
}
// |x| <= |y|
for (int y = d; y <= u; y++) {
if (y % 2 == 0) {
int L = max(l, -abs(y));
int R = min(r, abs(y));
int C = R - L + 1;
ans += max(C, 0);
}
}
cout << ans << '\n';
}