1152 - Expected value of the expressio
You are given an expression: A0O1A1O2A2⋯OnAnA0O1A1O2A2⋯OnAn, where Ai(0≤i≤n)Ai(0≤i≤n) represents number, Oi(1≤i≤n)Oi(1≤i≤n) represents operator. There are three operators, &,|,^&,|,^, which means and,or,xorand,or,xor, and they have the same priority.
The ii-th operator OiOi and the numbers AiAi disappear with the probability of pipi.
Find the expected value of an expression.
input:
The first line contains only one integer n(1≤n≤1000)n(1≤n≤1000).The second line contains n+1n+1 integers Ai(0≤Ai<220)Ai(0≤Ai<220).The third line contains nn chars OiOi.The fourth line contains nn floats pi(0≤pi≤1)pi(0≤pi≤1).
out:
Output the excepted value of the expression, round to 6 decimal places.
#include<string.h>
#include<math.h>
#define LL long long
const int MAX=1005;
int Ai[MAX];
double p[MAX];
int a[MAX];
char op[MAX][3];
double dp[MAX][3];
int main()
{
int n;
int i,j;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<=n;i++)scanf("%d",&Ai[i]);
for(int i=1;i<=n;i++)scanf("%s",op[i]);
for(int i=1;i<=n;i++)scanf("%lf",&p[i]);
double output=0;
for(i=0;i<=20;i++)
{
for(int j=0;j<=n;j++)
{
if((Ai[j]&(1<<i))>0) //&优先级低于判断符号
{
a[j]=1;
}
else a[j]=0;
}
dp[0][a[0]]=1;
for(int j=1;j<=n;j++)
{
dp[j][0]=dp[j-1][0]*p[j];
dp[j][1]=dp[j-1][1]*p[j];
if(op[j][0]=='|')
{
if(a[j]==0)
{
dp[j][0]+=dp[j-1][0]*(1-p[j]);
dp[j][1]+=dp[j-1][1]*(1-p[j]);
}
if(a[j]==1)
{
dp[j][1]+=dp[j-1][0]*(1-p[j]);
dp[j][1]+=dp[j-1][1]*(1-p[j]);
}
}
if(op[j][0]=='&')
{
if(a[j]==0)
{
dp[j][0]+=dp[j-1][0]*(1-p[j]);
dp[j][0]+=dp[j-1][1]*(1-p[j]);
}
if(a[j]==1)
{
dp[j][0]+=dp[j-1][0]*(1-p[j]);
dp[j][1]+=dp[j-1][1]*(1-p[j]);
}
}
if(op[j][0]=='^')
{
if(a[j]==0)
{
dp[j][0]+=dp[j-1][0]*(1-p[j]);
dp[j][1]+=dp[j-1][1]*(1-p[j]);
}
if(a[j]==1)
{
dp[j][0]+=dp[j-1][1]*(1-p[j]);
dp[j][1]+=dp[j-1][0]*(1-p[j]);
}
}
}
}
printf("%.6lf\n",output);
}
return 0;
}