Olympiad in Informatics

BZOJ3450: Easy — Solution

Main Idea

A really nice problem, just right for a probability-and-expectation newbie like me to take on.

First, let \(dp[i]\) be the expected length ending at \(i\). Next, we notice that \((x+1)^2-x^2=2x+1\). If we require consecutive runs, then depending on the character, there are the following transitions:

  1. When \(str[i]='o'\), \(dp[i] = dp[i-1]+1\), and the contribution to the answer is \(2dp[i-1]+1\).
  2. When \(str[i]='x'\), no transition is made, and the contribution to the answer is \(0\).
  3. When \(str[i]='?'\), the probability of it being \(o\) is \(\frac{1}{2}\), the transition is \(dp[i]=\frac{dp[i-1]+1}{2}\), and the contribution to the answer is \(\frac{2dp[i-1]+1}{2}\).

Just hack it out from there.

Code

// BZ3450.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 300200;
int n;
char str[MAX_N];
long double dp[MAX_N], ans;
int main()
{
    scanf("%d%s", &n, str + 1);
    dp[0] = 0;
    for (int i = 1; i <= n; i++)
        switch (str[i])
        {
        case 'o':
            dp[i] = dp[i - 1] + 1;
            ans += 2 * dp[i - 1] + 1;
            break;
        case 'x':
            dp[i] = 0;
            break;
        case '?':
            dp[i] = 1.0 * (dp[i - 1] + 1) / 2.0;
            ans += 1.0 * (2.0 * dp[i - 1] + 1) / 2.0;
            break;
        }
    printf("%.4Lf", ans);
    return 0;
}