跳到正文

题解

题解:P2025 Dirichlet 半在线卷积

RAYMOND_7约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年3月21日
收录
2026年2月28日
更新
2026年11月10日
篇幅
约 3 分钟
题目
P2025

版本

  1. v1当前

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

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

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

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

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

C++
#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;
}
原文
存档评论3 条抓取于