跳到正文

题解

题解:CF1946F Nobody is needed

Claire0918约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年9月22日
收录
2026年9月22日
更新
2026年11月12日
篇幅
约 4 分钟
题目
CF1946F

版本

  1. v1当前

注意到左端点变化答案完全不同,于是我们考虑将询问挂在左端点上,维护 fif_i 表示当前以 ii 结尾的答案,查询即求 ∑i=lrfi\sum_{i = l}^{r} f_i,每次在左侧加入一个点。加入 ii 后,首先 fi←1f_i \gets 1,随后枚举每个 ai∣aja_i \mid a_j 的 jj,考虑 aj∣ak,aj<aka_j \mid a_k, a_j < a_k 且 j<kj < k 的 kk,就有 fk←fjf_k \gets f_j,维护每个 fkf_k 的增加量,最后再加到树状数组上。

暴力枚举的复杂度为满足 1≤i≤j≤k≤n1 \leq i \leq j \leq k \leq n 且 i∣j,j∣ki \mid j, j \mid k 的三元组 (i,j,k)(i, j, k) 数量,即

∑i=1n∑i∣j⌊nj⌋=∑i=1n∑j=1⌊ni⌋⌊⌊ni⌋j⌋=O(∑i=1n⌊ni⌋log⁡⌊ni⌋)=O(nlog⁡2n)\sum_{i = 1}^{n} \sum_{i \mid j} \lfloor\frac{n}{j}\rfloor = \sum_{i = 1}^{n} \sum_{j = 1}^{\lfloor\frac{n}{i}\rfloor}\lfloor\frac{\lfloor\frac{n}{i}\rfloor}{j}\rfloor = \mathcal{O}(\sum_{i = 1}^{n} \lfloor\frac{n}{i}\rfloor\log\lfloor\frac{n}{i}\rfloor) = \mathcal{O}(n\log^2n)

我们还有 O(nlog⁡n)\mathcal{O}(n\log n) 次树状数组修改,于是总复杂度就是 O(nlog⁡2n)\mathcal{O}(n\log^2n)。

Code:

C++
#include<bits/stdc++.h>
#define mem(a, v) memset(a, v, sizeof(a))

using namespace std;

const int maxn = 1e6 + 10, maxq = 1e6 + 10;

int t, n, q;
int a[maxn], pos[maxn], d[maxn];
long long res[maxq];
vector<pair<int, int> > qry[maxn];

namespace BIT{
    long long tree[maxn];
    inline int lbw(int x){
        return x & -x;
    }
    inline void add(int x, int k){
        for (;x <= n; tree[x] += k, x += lbw(x));
    }
    inline long long query(int x){
        long long res = 0;
        for (;x; res += tree[x], x -= lbw(x));
        return res;
    }
}

using namespace BIT;

int main(){
    scanf("%d", &t);
    while (t--){
        scanf("%d %d", &n, &q);
        for (int i = 1; i <= n; i++){
            scanf("%d", &a[i]), pos[a[i]] = i, tree[i] = 0, qry[i].clear();
        }
        for (int i = 1; i <= q; i++){
            int l, r;
            scanf("%d %d", &l, &r), qry[l].push_back(make_pair(i, r));
        }
        for (int i = n; i; i--){
            d[a[i]] = 1;
            for (int x = a[i]; x <= n; x += a[i]){
                for (int y = x << 1; y <= n; y += x){
                    pos[y] > pos[x] && (d[y] += d[x]);
                }
            }
            for (int x = a[i]; x <= n; x += a[i]){
                add(pos[x], d[x]), d[x] = 0;
            }
            for (auto x: qry[i]){
                res[x.first] = query(x.second);
            }
        }
        for (int i = 1; i <= q; i++){
            printf("%lld ", res[i]);
        }
        putchar('\n');
    }

return 0;
}
原文