题目意思
给出一个空数列a,从1到m随机选一个数进入a数组,当a数组中全部数的gcd是1的时候退出程序,问平均期望长度。
解题思路
数论,期望dp
[参考1,zzugzx大佬](https://blog.nowcoder.net/n/6fc91cc5671f457d9389dc3bd9303aa1)
[参考2,superj7大佬](https://blog.nowcoder.net/n/fb90d1cb191a4432bb908a53857c8a25)
和gcd有关显然加入数据不会把当前最小的gcd减小,只会不变和变小,所以考虑动态规划解题。
剩下的就是推化式子了……这对一个高数要挂科的小白来说。。太太太困难了。
迷迷糊糊的看出来预处理数组,期望dp,其余的就是参考第二位大佬的式子了。。
#pragma GCC target("avx,sse2,sse3,sse4,popcnt") #pragma GCC optimize("O2,O3,Ofast,inline,unroll-all-loops,-ffast-math") #include <bits/stdc++.h> using namespace std; #define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0) #define all(vv) (vv).begin(), (vv).end() #define endl "\n" typedef long long ll; typedef unsigned long long ull; typedef long double ld; const int MOD = 1e9 + 7; inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar()) s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; } inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-'); int cnt = 0; while (tmp > 0) { F[cnt++] = tmp % 10 + '0'; tmp /= 10; } while (cnt > 0)putchar(F[--cnt]); } inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; } ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; } inline int lowbit(int x) { return x & (-x); } const int N = 1e5 + 7; ll dp[N]; vector<ll> d[N], cnt[N]; int main() { int n = read(); // 预处理 for (int i = 1; i <= n; ++i) for (int j = i; j <= n; j += i) d[j].push_back(i), cnt[j].push_back(0); for (int i = 1; i <= n; ++i) for (int j = d[i].size() - 1; ~j; --j) { cnt[i][j] = n / d[i][j]; for (int k = j + 1; k < d[i].size(); ++k) if (d[i][k] % d[i][j] == 0) cnt[i][j] -= cnt[i][k]; } //期望dp dp[1] = 0; for (int i = 2; i <= n; ++i) { ll sum = 0, x = 0; for (int j = 0; j < d[i].size(); ++j) if (d[i][j] == i) (sum += cnt[i][j]) %= MOD; else (x += dp[d[i][j]] * cnt[i][j] % MOD) %= MOD; dp[i] = (x + n) % MOD * qpow((n - sum + MOD) % MOD, MOD - 2, MOD) % MOD; } ll ans = 0; for (int i = 1; i <= n; ++i) (ans += dp[i] + 1) %= MOD; (ans *= qpow(n, MOD - 2, MOD)) %= MOD; write(ans); return 0; }