题解:P2025 Dirichlet 半在线卷积

· · 题解

半在线卷积,其实就是先分治,计算左区间答案,然后对右区间贡献,发现此时右区间内部没有贡献,不需要额外递归,从而降低时间复杂度。

本题中,如果我们得出了 \large\lfloor\frac{n}{2}\rfloor 以内答案,那么后一半是可以直接计算的,暴力的复杂度为 O(n\ln n) ,并不能通过任何测试点。

考虑优化,不难发现 f\otimes\varphi=f\otimes Id \otimes \mu,前面是个完全积性函数,可以在高维前缀和的过程中统计贡献,后面相当于高维差分。

具体的,当高位前缀和中乘上一个质数 p_i 做贡献时,我们直接把原来的前缀和乘上一个 p_i 就完成了和 Id 函数做卷积的过程。

复杂度应该是 O(n \ln \ln n) 的,不过常数有点大。

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
#include <ctime>

using namespace std;

#define ui unsigned
#define PII pair<int,int>
#define x first
#define y second
#define For(i, l, r) for(int i = l; i <= r; i ++)
#define Rep(i, l, r) for(int i = l; i >= r; i --)

bool START;

const int N=5e7+50;

int n,m,phi[N],cnt,p[N/10];
bool ok[N];
ui f[N],a[N],ans;

void solve(int n)
{
    if(n<=1)return ;
    solve(n/2);
    For(i,1,n)a[i]=0;
    For(i,1,n/2)a[i]=f[i];
    For(i,1,cnt)
    {
        if(p[i]>n)break;
        for(int j=1;j*p[i]<=n;j++)a[j*p[i]]+=a[j]*p[i];
    }
    For(i,1,cnt)
    {
        if(p[i]>n) break;
        for(int j=n/p[i];j;j--)a[j*p[i]]-=a[j];
    }
    For(i,n/2+1,n)f[i]=a[i];
}

bool ENDPOS = 0;
signed main()
{
    double chu = clock();
    cin>>n;
    f[1]=1;phi[1]=1;
    For(i,2,n)
    {
        if(!ok[i])p[++cnt]=i,phi[i]=i-1;
        For(j,1,cnt)
        {
            if(i*p[j]>n)break;
            ok[i*p[j]]=1;if(i%p[j]==0)break;
        }
    }
    solve(n);
    For(i,1,n)ans^=f[i];
    printf("%u\n", ans);
    cerr << "Time = " << (clock() - chu) / CLOCKS_PER_SEC << endl;
    cerr << (&ENDPOS - &START) * 1.0 / 1024 / 1024 << endl; return 0;
}