You're playing a game called Osu! Here's a simplified version of it. There aren clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence ofn characters "O" and "X".
Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 22 + 32 + 22 = 17. If there are no correct clicks in a play then the score for the play equals to 0.
You know that the probability to click the i-th(1 ≤ i ≤ n) click correctly ispi. In other words, thei-th character in the play sequence haspi probability to be "O",1 - pi to be "X". You task is to calculate the expected score for your play.
The first line contains an integer n (1 ≤ n ≤ 105) — the number of clicks. The second line containsn space-separated real numbers p1, p2, ..., pn(0 ≤ pi ≤ 1).
There will be at most six digits after the decimal point in the given pi.
Print a single real number — the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed10 - 6.
3 0.5 0.5 0.5
2.750000000000000
4 0.7 0.2 0.1 0.9
2.489200000000000
5 1 1 1 1 1
25.000000000000000
For the first example. There are 8 possible outcomes. Each has a probability of 0.125.
- "OOO" → 32 = 9;
- "OOX" → 22 = 4;
- "OXO" → 12 + 12 = 2;
- "OXX" → 12 = 1;
- "XOO" → 22 = 4;
- "XOX" → 12 = 1;
- "XXO" → 12 = 1;
- "XXX" → 0.
So the expected score is
题意,给出每个位置O出现的概率,求连续O的个数的平方和的数学期望。
思路:(不是我想出来的,大牛教的)设ai为第i段连续O的长度,∑ai^2 = ∑[ ai+ ai*(ai-1) ] = ∑ ai*(ai-1) + ∑ai = ∑ C(ai, 2)*2 + ∑ai
这样就转化为长度大于1的连续段数*2+O的个数
例如:OOXOXOOO,它的值是4+1+9=14
转化后计算则为4*2+6=14 (4段长度大于1的连续段分别为1~2、5~6、5~7、6~7,再加上O的个数6)
dp[i]表示以i结尾的连续O的段数的期望(这里包括长度为1的,上例中,dp[1]=1,dp[2]=2,dp[7]=2,dp[8]=3),状态转移则为dp[i]=dp[i-1]*p[i]+p[i];
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=100005;
double p[maxn], dp[maxn];
int n;
int main(){
//freopen("1.txt", "r", stdin);
int i;
while(scanf("%d", &n)!=EOF){
double ans=0;
for(i=1; i<=n; i++){
scanf("%lf", &p[i]);
ans+=p[i];
}
dp[0]=0;
for(i=1; i<=n; i++){
dp[i]=dp[i-1]*p[i]+p[i];
ans+=(dp[i]-p[i])*2;
}
printf("%.7f\n", ans);
}
return 0;
}