UVa 11762 Race to 1 (数学期望 + 记忆化搜索)

题意:给定一个整数 n ,然后你要把它变成 1,变换操作就是随机从小于等于 n 的素数中选一个p,如果这个数是 n 的约数,那么就可以变成 n/p,否则还是本身,问你把它变成 1 的数学期望是多少。

析:一个很明显的期望DP,dp[i] 表示把 i 变成 1 的期望是多少,枚举每一种操作,列出表达式,dp[i] = ∑dp[i/x]/q + p/q*dp[i] + 1,其中 x 表示枚举的素数,然后 p 表示不是 i 的约数个数,q 是小于等于 n 的素数个数,然后变形,可以得到 dp[i] = (∑dp[i/x] + q) / (q-p),可以用记忆化搜索来做。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#include <list>
#include <assert.h>
#include <bitset>
#include <numeric>
#define debug() puts("++++")
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a, b, sizeof a)
#define sz size()
#define pu push_up
#define pd push_down
#define cl clear()
#define lowbit(x) -x&x
//#define all 1,n,1
#define FOR(i,x,n) for(int i = (x); i < (n); ++i)
#define freopenr freopen("in.in", "r", stdin)
#define freopenw freopen("out.out", "w", stdout)
using namespace std; typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e17;
const double inf = 1e20;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1000000 + 10;
const int maxm = 100 + 2;
const LL mod = 100000000;
const int dr[] = {-1, 1, 0, 0, 1, 1, -1, -1};
const int dc[] = {0, 0, 1, -1, 1, -1, 1, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c) {
return r >= 0 && r < n && c >= 0 && c < m;
} double dp[maxn];
bool vis[maxn];
int prime[maxn], cnt; double dfs(int x){
if(x == 1) return 0.;
double &ans = dp[x];
if(ans > 0.) return ans;
ans = 0.;
int q = 0, p = 0;
for(int i = 0; i < cnt && prime[i] <= x; ++i, ++q)
if(x % prime[i] == 0) dp[x] += dfs(x / prime[i]);
else ++p;
ans += q;
ans /= q - p;
return ans;
} int main(){
for(int i = 2; i < maxn; ++i) if(!vis[i]){
prime[cnt++] = i;
if(i > 1000) continue;
for(int j = i*i; j < maxn; j += i) vis[j] = 1;
}
int T; cin >> T; ms(dp, 0);
for(int kase = 1; kase <= T; ++kase){
scanf("%d", &n);
printf("Case %d: %.6f\n", kase, dfs(n));
}
return 0;
}

  

上一篇:20165320 第四次实验 Android开发


下一篇:UVa 1252 Twenty Questions (状压DP+记忆化搜索)