题解:P15765 [JAG 2025 Summer Camp #1] Sum of Floor(N/ij)

· · 题解

双倍经验和三倍经验。

枚举自然是简单的,但是整除分块还是最直观的。

以下记所求式子为 S。

设:

F(n)=\sum_{j=1}^{n} \left\lfloor \frac{n}{j} \right\rfloor

则容易注意到 S 可化为:

\begin{aligned} S&=\sum_{i=1}^{N} \sum_{j=1}^{N} \left\lfloor \frac{\lfloor \frac{N}{i} \rfloor}{j} \right\rfloor\\ &=\sum_{i=1}^{N} F(\left\lfloor \frac{N}{i} \right\rfloor) \end{aligned}

于是 F(n) 和 S 都可以使用整除分块计算,然而单测试点多组数据,所以这样做会超时,考虑优化。

事实上,对于 F(n),我们有一个常数比整除分块小的经典求法:

F(n)=2\sum^{\lfloor \sqrt{n}\rfloor}_{j=1}\left\lfloor \frac{n}{j}\right\rfloor-\lfloor \sqrt{n}\rfloor^2

因此我们可以在计算 F(n) 时使用该求法,计算 S 时再整除分块,只要不开那么多 long long 就足以通过了。

想要进一步缩小常数只需使用记忆化大法,每计算一个 F(n) 就将其值用 map 存起来,避免重复的 F(n) 计算多次。这方法对于此题有着显著的优化效果。

整体时间复杂度大概是 O(Tn^{\frac{2}{3}})。

::::success[AC code & 提交记录]

//edit by devc++
//by gitxiaozheng/dakada
#include<bits/stdc++.h>
using namespace std;
#define L long long
#define iotype L  //zigai
#define space putchar(' ')
#define enter putchar('\n')
inline iotype qcin();
void qcout(iotype);
map<L,L> fn;
inline L F(int n){
    if(fn[n]!=0){
        return fn[n];   //之前计算过的直接返回
    }
    L res=0ll;
    int m=sqrt(n);
    for(int i=1;i<=m;i++){
        res+=(L)(n/i);
    }
    return fn[n]=((res<<1)-m*m);  //记忆化
}
inline L S(int n){
    L res=0ll;
    for(int l=1,r;l<=n;l=r+1){
        r=n/(n/l);
        res+=1ll*(r-l+1)*F(n/l);
    }
    return res;
}
int main(){
    //Your code is here...
    for(int T=qcin();T;T--){
        int a=qcin();
        qcout(S(a)); 
        enter;
    }
    return 0;
}


inline iotype qcin(){
    iotype k=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-'){
            f=-1;
        }
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        k=k*10+c-'0';
        c=getchar();
    }
    return k*f;
}
void qcout(iotype x){
    static int num[20];
    int tot=0;
    if(x<0){
        putchar('-');
        x=-x;
    }
    while(x>=10){
        num[++tot]=x%10;
        x/=10;
    }
    putchar(x+'0');
    for(int i=tot;i>=1;i--){
        putchar(num[i]+'0');
    }
}
提交记录。