100213. 按距离统计房屋对数目 II - 力扣(LeetCode)
class Solution {
public:
vector<int> dif;
void add(int l, int r, int d) {
if (l > r) return;
dif[l] += d;
dif[r + 1] -= d;
return;
}
vector<long long> countOfPairs(int n, int x, int y) {
dif.resize(n + 5);
if (x > y) swap(x, y);
for (int i = 1; i <= n; i++) {
//add(1, i - 1, 1);
add(1, n - i, 2);
if (x + 1 >= y) continue;
if (i <= x) {
add(y - i, n - i, -2);
add(x - i + 1, x - i + 1 + n - y, 2);
}
else if (i > x && i < (y + x - 2) / 2) {
int j = (2 * i - x + 1 + y) / 2 + 1;
add(j - i, y - 1 - i, -2);
add(i - x + 2, i - x + 1 + y - j, 2);
}
else if (i > (y + x + 1) / 2 && i < y) {
add(i - x, i - 1, -2);
add(y - i + 1, y - i + x, 2);
}
else if (i >= y) {
int j = (y + x - 1) / 2;
add(i - j, i - x - 1, -2);
add(i - y + 2, i - y + 1 + j - x, 2);
}
}
vector<long long> ans(1, dif[1]);
for (int i = 2; i <= n; i++) {
ans.push_back(ans.back() + dif[i]);
}
return ans;
}
};
class Solution {
public:
vector<int> dif;
void add(int l, int r) {
dif[l]++, dif[r + 1]--;
return;
}
vector<long long> countOfPairs(int n, int x, int y) {
if (x > y) swap(x, y);
vector<long long> ans;
if (y - x < 2) {
for (int i = 1; i <= n; i++) ans.push_back((n - i) * 2);
return ans;
}
dif.resize(n + 5);
for (int i = 1; i < n; i++) {
if (i <= x) {
int j = (y + x + 1) / 2 + 1;
add(1, j - i - 1);
add(x - i + 2, x - i + y - j + 1);
add(x - i + 1, x - i + n - y + 1);
}
else if (i < (y + x) / 2) {
int j = i + (y - x + 1) / 2;
add(1, j - i);
add(i - x + 2, i - x + y - j);
add(i - x + 1, i - x + n - y + 1);
}
else add(1, n - i);
}
ans.push_back(2 * dif[1]);
for (int i = 2; i <= n; i++) {
ans.push_back(ans.back() + dif[i] * 2);
}
return ans;
}
};