LightOJ 1038 Race to 1 Again (概率DP,记忆化搜索)

题意:给定一个数 n,然后每次除以他的一个因数,如果除到1则结束,问期望是多少。

析:概率DP,可以用记忆公搜索来做,dp[i] = 1/m*sum(dp[j] + 1) + 1/m * (dp[i] + 1)  ==> dp[i] = (sum(dp[j]) + m) / (m-1)。其中m是因数个数。

代码如下:

#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>
#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 freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "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 = 1e16;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e5 + 10;
const int mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -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]; double dfs(int n){
if(dp[n] > -0.5) return dp[n];
if(1 == n) return dp[n] = 0.0;
if(n == 2 || n == 3) return dp[n] = 2.0;
dp[n] = 0.0;
int t = sqrt(n+0.5);
int cnt = 2;
for(int i = 2; i < t; ++i) if(n % i == 0){
dp[n] += dfs(n / i) + dfs(i);
cnt += 2;
}
if(n % t == 0){
if(n / t == t) dp[n] += dfs(t), ++cnt;
else dp[n] += dfs(t) + dfs(n/t), cnt += 2;
}
dp[n] += cnt;
return dp[n] = dp[n] / (cnt-1.0);
} int main(){
memset(dp, -1, sizeof dp);
int T; cin >> T;
for(int kase = 1; kase <= T; ++kase){
scanf("%d", &n);
printf("Case %d: %.10f\n", kase, dfs(n));
}
return 0;
}

  

上一篇:【bzoj1415】[Noi2005]聪聪和可可 期望记忆化搜索


下一篇:uva 11762 数学期望+记忆化搜索