UVA 11762 - Race to 1(概率)
UVA 11762 - Race to 1
题意:给定一个n,每次随即选择一个n以内的质数,假设不是质因子,就保持不变,假设是的话。就把n除掉该因子,问n变成1的次数的期望值
思路:tot为总的质数。cnt为质因子个数,那么f(n)=(1−cnt/tot)∗f(n)+∑f(n/prime)∗(1/tot),然后利用记忆化搜索去做就可以
代码:
#include <stdio.h> #include <string.h> const int N = 1000005; int t, n, prime[N], pn = 0, vis[N]; double f[N]; void get_table() { for (int i = 2; i < N; i++) { if (vis[i]) continue; prime[pn++] = i; for (int j = i; j < N; j += i) vis[j] = 1; } } double dfs(int n) { if (f[n] != -1) return f[n]; f[n] = 0; if (n == 1) return f[n]; int tot = 0, cnt = 0; for (int i = 0; i < pn && prime[i] <= n; i++) { tot++; if (n % prime[i]) continue; cnt++; f[n] += dfs(n / prime[i]); } f[n] = (f[n] + tot) / cnt; return f[n]; } int main() { get_table(); for (int i = 0; i < N; i++) f[i] = -1; int cas = 0; scanf("%d", &t); while (t--) { scanf("%d", &n); printf("Case %d: %.7lf\n", ++cas, dfs(n)); } return 0; }