跳到正文

题解

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

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

文章信息

收录
2026年5月13日
更新
2026年5月13日
篇幅
约 4 分钟
题目
P15765

版本

  1. v2当前
  2. v1

update:被指出时间复杂度分析错误,修改后重交。


这道题显然可以整除分块套整除分块,但是时间复杂度 O(Tn34)O(Tn^{\frac{3}{4}}),显然不可过。好像有人过了?

所以我们考虑将式子变形。对于原式,记 k=ijk=ij,我们发现当且仅当 k≤nk\leq n 的时候有贡献。于是我们可以考虑枚举 kk,这样就可以得到下面的这个式子:

∑k=1n⌊nk⌋d(k)\sum^{n}_{k=1}\left\lfloor\frac{n}{k}\right\rfloor d(k)

前面的一部分显然,d(k)d(k) 是这个 kk 会被选到的次数,即 kk 的正约数个数。直接用线性筛预处理是 O(n+Tn)O(n+T\sqrt{n}) 的,并不优秀。于是我们考虑摊平复杂度。

我们用线性筛预处理 BB 个数,那么就可以得出如下的时间复杂度:

首先,预处理是 O(B)O(B)。对于 n>Bn>B 的情况,我们可以使用整除分块来求 ∑i=1nd(i)\sum^{n}_{i=1}d(i)(这个想必大家都会吧,可以转化为 ∑i=1n⌊ni⌋\sum^{n}_{i=1}\lfloor\frac{n}{i}\rfloor),这个对于单点求值是 O(n)O(\sqrt{n}) 的。那么,总共会求多少次单点呢?注意到我们的每一个 nn,在整除分块中,对于 n>Bn>B 总共会贡献 nB\frac{n}{B} 次,然后我们可以使用一个哈希来存储已经求过的前缀和,就不会反复求了,所以时间复杂度是 O(nBn)O(\frac{n}{B}\sqrt n) 的。一共要求 TT 次,所以总时间复杂度是 O(TnBn)O(T\frac{n}{B}\sqrt n) 的。

但是由于使用了记忆化严重跑不满,并且随着 TT 的增加越来越跑不满,应该是有更严格的上界的。

取 B=n34B=n^{\frac{3}{4}} 可以做到最优时间复杂度 O(n34+Tn34)O(n^{\frac{3}{4}}+Tn^{\frac{3}{4}}),有一个根号是因为每一次查询的时候都要整除分块。可以通过加强版:https://www.luogu.com.cn/problem/U684999,虽然好像跑的比造数据的人慢……

C++
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;

const int N = 1e7 + 5;
unordered_map<int, int> sd;
bool isp[N];
int t, n, prime[N], cnt[N], d[N], tp;

void sieve(int n) {
	d[1] = 1;
	for(int i = 2; i <= n; i ++ ) {
		if(!isp[i]) prime[ ++ tp] = i, d[i] = 2, cnt[i] = 1;
		for(int j = 1; j <= tp && i * prime[j] <= n; j ++ ) {
			isp[i * prime[j]] = true;
			if(i % prime[j] == 0) {
				cnt[i * prime[j]] = cnt[i] + 1;
				d[i * prime[j]] = d[i] / (cnt[i] + 1) * (cnt[i] + 2);
				break;
			} else {
				cnt[i * prime[j]] = 1;
				d[i * prime[j]] = d[i] * d[prime[j]];
			}
		}
		d[i] += d[i - 1];
	}
}

int getd(int x) {
	if(x <= N - 5) return d[x];
	if(sd[x]) return sd[x];
	int ans = 0;
	for(int i = 1, j; i <= x; i = j + 1)
		j = x / (x / i), ans += (x / i) * (j - i + 1);
	return sd[x] = ans;
}

int solve(int x) {
	int ans = 0;
	for(int i = 1, j; i <= x; i = j + 1)
		j = x / (x / i), ans += (x / i) * (getd(j) - getd(i - 1));
	return ans;
}

signed main() {
	ios :: sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> t;
	sieve(N - 5);
	while(t -- ) {
		cin >> n;
		cout << solve(n) << endl;
	}
	return 0;
}
原文