A - Bags of Candies Gym - 102576A(min25筛,素数个数)

    科技2022-07-11  103

    题意: n个数,1~n。可以将两个gcd不为1的数分为一组,或者一个数分为一组,求最少分多少组。

    思路: 和牛客多校那个题很像 https://blog.csdn.net/tomjobs/article/details/107473587

    如果问的是方案数,那么可以把所有数按最小素因子分组,那么如果这个组的数目是奇数,则把第一个数和其两倍匹配,剩下的自己和自己匹配。否则就是偶数个,直接内部匹配。

    2的个数为n/2,那么可以保证除了1和大于n/2的素数,其他所有数都能匹配上(除非剩下的数为奇数,那就剩下了一个)。


    那么问题就成了怎么知道某个区间段的素数个数,数据范围1e11,这个可以用min25筛。

    我这里找到了MIN25本人的代码,巨快无比ORZ(100ms,VJ上本题最快)。

    #pragma optimize("-O3") #include <cstdio> #include <cassert> #include <cmath> #include <vector> using namespace std; typedef long long ll; using i64 = long long; int isqrt(i64 n) { return sqrtl(n); } __attribute__((target("avx"), optimize("O3", "unroll-loops"))) i64 prime_pi(const i64 N) { if (N <= 1) return 0; if (N == 2) return 1; const int v = isqrt(N); int s = (v + 1) / 2; vector<int> smalls(s); for (int i = 1; i < s; ++i) smalls[i] = i; vector<int> roughs(s); for (int i = 0; i < s; ++i) roughs[i] = 2 * i + 1; vector<i64> larges(s); for (int i = 0; i < s; ++i) larges[i] = (N / (2 * i + 1) - 1) / 2; vector<bool> skip(v + 1); const auto divide = [] (i64 n, i64 d) -> int { return double(n) / d; }; const auto half = [] (int n) -> int { return (n - 1) >> 1; }; int pc = 0; for (int p = 3; p <= v; p += 2) if (!skip[p]) { int q = p * p; if (i64(q) * q > N) break; skip[p] = true; for (int i = q; i <= v; i += 2 * p) skip[i] = true; int ns = 0; for (int k = 0; k < s; ++k) { int i = roughs[k]; if (skip[i]) continue; i64 d = i64(i) * p; larges[ns] = larges[k] - (d <= v ? larges[smalls[d >> 1] - pc] : smalls[half(divide(N, d))]) + pc; roughs[ns++] = i; } s = ns; for (int i = half(v), j = ((v / p) - 1) | 1; j >= p; j -= 2) { int c = smalls[j >> 1] - pc; for (int e = (j * p) >> 1; i >= e; --i) smalls[i] -= c; } ++pc; } larges[0] += i64(s + 2 * (pc - 1)) * (s - 1) / 2; for (int k = 1; k < s; ++k) larges[0] -= larges[k]; for (int l = 1; l < s; ++l) { int q = roughs[l]; i64 M = N / q; int e = smalls[half(M / q)] - pc; if (e < l + 1) break; i64 t = 0; for (int k = l + 1; k <= e; ++k) t += smalls[half(divide(M, roughs[k]))]; larges[0] += t - i64(e - l) * (pc + l - 1); } return larges[0] + 1; } void solve(ll N) { if(N == 1) { printf("1\n"); } else if(N == 2) { printf("2\n"); } else if(N == 3) { printf("3\n"); } else { ll num = prime_pi(N); ll num2 = prime_pi(N / 2); ll single = num - num2 + 1; printf("%lld\n",(N - single + 1) / 2 + single); } } int main() { int T;scanf("%d",&T); while(T--) { i64 N; scanf("%lld", &N); solve(N); } return 0; }
    Processed: 0.035, SQL: 8