题目链接:http://lightoj.com/volume_showproblem.php?problem=1038
给定一个n,然后每次可以找到n的一个因子x包括1和本身, 然后n=n/x,直到n为1为止,求次数期望。
dp[n]表示n到1的期望次数,例如dp[8] = (dp[1]+dp[2]+dp[4]+dp[8])*(1/4) + 1,化简得dp[8] = (dp[1]+dp[2]+dp[4] + 4) / 3;
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cstdio> 6 #include <vector> 7 #include <ctime> 8 #include <queue> 9 #include <list> 10 #include <set> 11 #include <map> 12 using namespace std; 13 #define INF 0x3f3f3f3f 14 typedef long long LL; 15 16 double dp[100010]; 17 double solve(int n) 18 { 19 if(dp[n] != -1) 20 return dp[n]; 21 double res = 0; 22 double con = 2; 23 for(int i = 2; i * i <= n; i++) 24 { 25 if(n % i != 0) 26 continue; 27 con++; 28 res += solve(i); 29 if(i * i != n){ 30 res += solve(n / i); 31 con++; 32 } 33 } 34 res += con; 35 res /= con-1; 36 dp[n] = res; 37 return res; 38 } 39 int main() 40 { 41 int t, n; 42 scanf("%d", &t); 43 for(int i = 1; i < 100001; i++) 44 dp[i] = -1; 45 dp[1] = 0; 46 for(int ca = 1; ca <= t; ca++) 47 { 48 scanf("%d", &n); 49 printf("Case %d: %.6f\n", ca, solve(n)); 50 } 51 return 0; 52 }
时间: 2024-11-08 21:08:23