题解 P4755 【Beautiful Pair】
提供一种题解区没有的做法。
依然是考虑分治,但是不需要令
对于一个区间
显然,
我们可以在
对于
对于
那么我们可以开两个树状数组,分别维护
计算贡献的时候,求出维护
注意,这里要离散化,考虑我们只用维护
总复杂度为
#include <cstdio>
#include <cctype>
#include <cstring>
#include <algorithm>
#define MAX_N (100000 + 5)
#define lowbit(x) ((x) & -(x))
using std::lower_bound;
using std::unique;
using std::sort;
using std::max;
using std::min;
int n;
int a[MAX_N], b[MAX_N * 4];
int s1[MAX_N * 4], s2[MAX_N * 4], cnt;
long long ans;
template <typename T>
void Read(T &x) {
x = 0;
char ch = getchar();
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
}
template <typename T>
void Write(T x) {
if (x >= 10) Write(x / 10);
putchar(x % 10 + '0');
}
void Insert(int *s, int pos) {
for (; pos <= cnt; pos += lowbit(pos))
++s[pos];
}
void Delete(int *s, int pos) {
for (; pos <= cnt; pos += lowbit(pos))
--s[pos];
}
int Count(int *s, int pos) {
int res = 0;
for (; pos; pos -= lowbit(pos))
res += s[pos];
return res;
}
void Solve(int l, int r) {
if (l == r) {
if (a[l] == 1) ++ans;
return;
}
int mid = l + r >> 1;
Solve(l, mid);
Solve(mid + 1, r);
// 离散化
cnt = 0;
for (int i = mid, max1 = 0; i >= l; --i) {
max1 = max(max1, a[i]);
b[++cnt] = max1 / a[i];
}
for (int i = mid + 1, max1 = a[mid], max2 = 0, j = mid; i <= r; ++i) {
max2 = max(max2, a[i]);
while (l <= j && max1 < max2) {
b[++cnt] = a[j];
max1 = max(max1, a[--j]);
}
b[++cnt] = a[i];
b[++cnt] = max2 / a[i];
}
sort(b + 1, b + cnt + 1);
cnt = unique(b + 1, b + cnt + 1) - b - 1;
// 计算贡献
for (int i = mid, max1 = 0; i >= l; --i) {
max1 = max(max1, a[i]);
Insert(s1, lower_bound(b + 1, b + cnt + 1, max1 / a[i]) - b);
}
for (int i = mid + 1, max1 = a[mid], max2 = 0, j = mid; i <= r; ++i) {
max2 = max(max2, a[i]);
while (l <= j && max1 < max2) {
Delete(s1, lower_bound(b + 1, b + cnt + 1, max1 / a[j]) - b);
Insert(s2, lower_bound(b + 1, b + cnt + 1, a[j]) - b);
max1 = max(max1, a[--j]);
}
ans += Count(s1, cnt) - Count(s1, lower_bound(b + 1, b + cnt + 1, a[i]) - b - 1);
ans += Count(s2, lower_bound(b + 1, b + cnt + 1, max2 / a[i]) - b);
}
// 清空树状数组
for (int i = mid, max1 = 0; i >= l; --i) {
max1 = max(max1, a[i]);
Delete(s1, lower_bound(b + 1, b + cnt + 1, max1 / a[i]) - b);
}
for (int i = mid + 1, max1 = a[mid], max2 = 0, j = mid; i <= r; ++i) {
max2 = max(max2, a[i]);
while (l <= j && max1 < max2) {
Insert(s1, lower_bound(b + 1, b + cnt + 1, max1 / a[j]) - b);
Delete(s2, lower_bound(b + 1, b + cnt + 1, a[j]) - b);
max1 = max(max1, a[--j]);
}
}
}
int main() {
Read(n);
for (int i = 1; i <= n; ++i) {
Read(a[i]);
b[i] = a[i];
}
Solve(1, n);
Write(ans);
return 0;
}