拋硬幣 Flipping Coins(Gym - 101606F)
----------------------------------------------------------------------------------------------------------------------
題意:給出N個硬幣,開始均反面朝上。每次挑出其中一個拋,連續K次,求正面朝上的最大數學期望。
----------------------------------------------------------------------------------------------------------------------
由於是求最大數學期望,所以每次拋硬幣即要優先選擇反面硬幣
所以只有兩種挑選硬幣的情況:
1.正面數量為 0 ~ n-1 ,選擇反面硬幣拋,拋出結果正面數量比原本 +1 或 不變
2.正面數量為 n,只能夠選擇正面硬幣拋,拋出結果正面數量比原本 -1 或 不變
----------------------------------------------------------------------------------------------------------------------
設 dp[i][j] 表示: 第 i 次拋硬幣後, j 個硬幣正面朝上的概率
1.當 j < n 時,dp[i][j]的概率一分為二,各給dp[i+1][j]和dp[i+1][j+1],即
for(int j=0;j<n;j++){ dp[i+1][j]+=dp[i][j]/2; dp[i+1][j+1]+=dp[i][j]/2; }
2.當 j == n 時,dp[i][j]的概率一分為二,各給dp[i+1][j]和dp[i+1][j-1],即
dp[i+1][n]+=dp[i][n]/2; dp[i+1][n-1]+=dp[i][n]/2;
如此即可求出n個硬幣拋k次的各個正面朝上的概率,最後求數學期望即可
附:n=2,k=4時的dp轉移表格:
1 #include <stdio.h> 2 #include <math.h> 3 #include <string.h> 4 #include <algorithm> 5 #include <iostream> 6 #include <queue> 7 #include <stack> 8 #include <functional> 9 #define INF 0x3f3f3f3f 10 using namespace std; 11 typedef long long ll; 12 double dp[410][410], ans; 13 int main(){ 14 int n, k; 15 while (~scanf("%d %d", &n, &k)){ 16 for (int i = 0; i <= 400; i++) 17 for (int j = 0; j <= 400; j++) 18 dp[i][j] = 0; 19 dp[0][0] = 1; 20 for (int i = 0; i < k; i++){ 21 for (int j = 0; j < n; j++){ 22 dp[i + 1][j] += dp[i][j] * 0.5; 23 dp[i + 1][j + 1] += dp[i][j] * 0.5; 24 } 25 dp[i + 1][n] += dp[i][n] * 0.5; 26 dp[i + 1][n - 1] += dp[i][n] * 0.5; 27 } 28 ans = 0; 29 for (int i = 1; i <= n; i++) 30 ans += i*dp[k][i]; 31 printf("%.8lf\n", ans); 32 } 33 return 0; 34 }AC代碼
拋硬幣 Flipping Coins(Gym - 101606F)