题意:对于一个数 ,给定n次位运算,每次位运算有不发生的概率,问你最后的期望值是多少。。。
解题思路:对于每一位进行计算,那它就是线性结构,而非树形结构,大大简化了运算
解题代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <math.h> 5 int num[205][22]; 6 double dp[3][25]; 7 char str[1005]; 8 void print() 9 { 10 for(int i = 1; i <= 20 ; i ++) 11 printf("%.3lf ",dp[0][i]); 12 printf(" "); 13 for(int i = 1; i <= 20 ; i ++) 14 printf("%.3lf ",dp[1][i]); 15 printf(" "); 16 } 17 int main() 18 { 19 int n ,Case = 0; 20 while(scanf("%d",&n) != EOF) 21 { 22 Case ++; 23 memset(num,0,sizeof(num)); 24 int maxn =0 ; 25 for(int i = 1; i <= n+1; i ++) 26 { 27 int temp ; 28 scanf("%d",&temp); 29 int t = 0 ; 30 while(temp >= 2) 31 { 32 t++ ; 33 num[i][t] = temp %2;; 34 temp = temp /2; 35 36 } 37 38 t++; 39 if(t > maxn) 40 maxn = t; 41 num[i][t] = temp ; 42 43 } 44 memset(dp,0,sizeof(dp)); 45 for(int i = 1; i <= maxn ; i ++) 46 { 47 if(num[1][i] == 0 ) 48 dp[0][i] = 1; 49 else dp[1][i] = 1; 50 } 51 getchar(); 52 gets(str); 53 int p = 0 ; 54 55 for(int i = 2 ; i <= n+1; i ++) 56 { 57 58 double k ; 59 scanf("%lf",&k); 60 if(str[p] == '&') 61 { 62 for(int j = 1 ; j <= maxn ; j ++) 63 { 64 if(num[i][j] == 0) 65 { 66 double temp = dp[1][j] *(1-k); 67 dp[1][j] -= temp; 68 dp[0][j] = 1 - dp[1][j]; 69 } 70 } 71 } 72 else if(str[p] == '|') 73 { 74 75 for(int j = 1 ; j <= maxn ; j ++) 76 { 77 if(num[i][j] == 1) 78 { 79 double temp = dp[0][j] *(1-k); 80 dp[0][j] -= temp; 81 dp[1][j] = 1 - dp[0][j]; 82 } 83 84 } 85 86 } 87 else 88 { 89 for(int j = 1 ; j <= maxn; j ++) 90 { 91 if(num[i][j] == 1) 92 { 93 double temp1 = dp[1][j] *(1-k) ; 94 double temp2 = dp[0][j] *(1-k) ; 95 dp[1][j] = dp[1][j] - temp1 + temp2; 96 dp[0][j] = 1 - dp[1][j] ; 97 } 98 } 99 100 } 101 p += 2 ; 102 103 } 104 double ans = 0 ; 105 for(int i = 1; i<= maxn ; i ++) 106 { 107 ans += dp[1][i]*pow(2.0,i-1); 108 } 109 printf("Case %d: %.6f ",Case,ans); 110 } 111 return 0 ; 112 }