题解
集合
1 条题解
-
0
1. 解题思路
筛出不小于p的质数,对每个质数把区间内全部倍数合并,最后统计代表元数量。
2. 坑点和注意事项
b≤10^5。首个倍数为向上取整(a/x)*x;用值减a作下标,质数没有至少两个区间倍数时无需合并。
3. 复杂度
- 时间复杂度:O(b log log b+b log b α(b)) 上界。
- 空间复杂度:O(b)。
/* 思路:筛出不小于p的质数,对每个质数把区间内全部倍数合并,最后统计代表元数量。 关键规则与坑点:b≤10^5。首个倍数为向上取整(a/x)*x;用值减a作下标,质数没有至少两个区间倍数时无需合并。 时间复杂度:O(b log log b+b log b α(b)) 上界。空间复杂度:O(b)。 */ #include <bits/stdc++.h> using namespace std; struct DSU { int p[200005], s[200005]; DSU(int n) { iota(p, p + n, 0); fill(s, s + n, 1); } int find(int x) { while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; } return x; } void join(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (s[x] < s[y]) swap(x, y); p[y] = x; s[x] += s[y]; } }; int main() { int a, b, p; cin >> a >> b >> p; DSU d(b - a + 1); static bool prime[100005]; fill(prime, prime + b + 1, true); prime[0] = prime[1] = false; for (int x = 2; x <= b; x++) if (prime[x]) { for (int j = 2 * x; j <= b; j += x) prime[j] = false; if (x >= p) { int first = (a + x - 1) / x * x; for (int y = first + x; y <= b; y += x) d.join(first - a, y - a); } } int count = 0; for (int x = 0; x <= b - a; x++) count += d.find(x) == x; cout << count << '\n'; }
- 1