题解:CF1946F Nobody is needed
题解:CF1946F Nobody is needed
省流:离线查询 + DP + 树状数组。
思路
首先想到是预处理,那么就分两种:
第一种
维护
但是这种情况会有多算,例如,排列为
此时
但区间内的合法子序列只有
多算的子序列为
第二种
把原本的查询按照左端点从大到小排序,右端点的顺序任意。
这样做的原因是,对于查询
具体做法
维护
所以在左端点扩的时候,只需要把所有满足
再用 BIT 维护
询问 bit.Query(r[i]) - bit.Query(l[i - 1])。
时间复杂度
由于
由调和级数可得,DP 转移的复杂度不会超过
树状数组的更新复杂度是
每次更新和查询的时间复杂度均为
空间复杂度为
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1000010;
struct Query {
int id, r;
};
LL f[N], ans[N];
vector<Query> qs[N];
int n, q, a[N], pos[N];
struct BIT {
LL tr[N];
int LowBit(int x) {
return x & -x;
}
void Add(int x, LL v) {
for (int i = x; i <= n; i += LowBit(i)) tr[i] += v;
}
LL Sum(int x) {
LL ret = 0LL;
for (int i = x; i; i -= LowBit(i)) ret += tr[i];
return ret;
}
};
BIT bit;
void Solve() {
scanf("%d%d", &n, &q);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
pos[a[i]] = i;
qs[i].clear();
}
for (int i = 1, l, r; i <= q; ++i) {
scanf("%d%d", &l, &r);
qs[l].push_back({i, r});
}
memset(bit.tr, 0, (n + 1) * sizeof(LL));
for (int i = n; i >= 1; --i) {
f[a[i]] = 1LL;
for (int j = a[i]; j <= n; j += a[i]) {
if (pos[j] < i) continue;
for (int k = 2 * j; k <= n; k += j) {
if (pos[k] < pos[j]) continue;
f[k] += f[j];
}
}
for (int j = a[i]; j <= n; j += a[i]) {
if (pos[j] >= i) bit.Add(pos[j], f[j]);
f[j] = 0LL;
}
for (auto [id, r] : qs[i]) {
ans[id] = bit.Sum(r) - bit.Sum(i - 1);
}
}
for (int i = 1; i <= q; ++i) {
printf("%lld%c", ans[i], " \n"[i == q]);
}
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
Solve();
}
return 0;
}