BZOJ2554: Color — Solution
Main Idea
This problem is so hard to wrap my head around. Let me think.
First, we need to turn this problem into a binary problem: we can enumerate the final color and then compute each case separately. Say the final color is white and every other color is black. Once it's converted into this problem, we can think about the transitions.
First, a state can be described directly by the number of white ones, \(x\). In state \(x\), we find that there are \(x(n - x)\) choices that make the color counts change, so the probability of a change is \(g_x = \frac{x(n - x)}{n(n - 1)}\), and the expected number of steps for a change is \(\frac{1}{g_x}\) (because \(x\) stays the same). When a change happens, \(x += 1\) and \(x -= 1\) are equally likely (because flipping it around gives a one-to-one correspondence).
So, if we only consider this binary problem and let \(f_x\) be the expected number of steps for everything to turn white, we get:
\[ f_x = \frac{f_{x - 1} + f_{x + 1}}{2} + g_x \]
It looks like there's a cycle, but we notice one property: at the boundaries, when \(x = 0, x = n\), \(f_x\) is \(0\). Then, moving on to \(f_1 = \frac{f_2}{2} + g_1\), we get \(f_2 = 2f_1 - 2g_1\). We find that recursing like this, every \(f_x\) can be expressed in the form \(f_x = af_1 + b\) (a bit like Gaussian elimination on a tree). Once the recurrence reaches \(f_n\), we can work back.
However, even after getting this, it's still not the final answer; it's only the answer to the binary problem. To compute the final overall probability, we also need to add a condition, namely decreeing that it must end up as one particular color. We just need to multiply by \( \frac{cnt}{n} \).
Code
// BZ2554.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e4 + 200;
int n, cnt[26];
char str[MAX_N];
double ai[MAX_N], bi[MAX_N], f[MAX_N], g[MAX_N], ans;
int main()
{
scanf("%s", str + 1), n = strlen(str + 1);
for (int i = 1; i <= n; i++)
cnt[str[i] - 'A']++;
for (int i = 1; i <= n; i++)
g[i] = 1.0 * i / n;
ai[1] = 1, bi[1] = 0;
for (int i = 1; i < n; i++)
{
ai[i + 1] = (ai[i] - ai[i - 1] * (i - 1) / (2 * i)) * (2 * i) / (i + 1);
bi[i + 1] = (bi[i] - bi[i - 1] * (i - 1) / (2 * i) - double(n * (n - 1)) / double(2 * i * (n - i))) * (2 * i) / (i + 1);
}
f[1] = -bi[n] / ai[n];
for (int i = 0; i < 26; i++)
ans += g[cnt[i]] * (ai[cnt[i]] * f[1] + bi[cnt[i]]);
printf("%.1lf\n", ans);
return 0;
}