---
id: 1151
lang: en
translation_of: index.md
source_sha256: 87e5fcd41d203477b938b85c6f7c08a4505ebc7c55231f681c6002d126dce523
title: "Codeforces Round #551 (Div. 2) Problem-Solving Report (CF1153)"
description: "Solutions to CF1153 C, D and F: greedy bracket filling, a greedy tree DP over min/max nodes, and an expected-length sum over pairings."
tags: ["OI","DP","Trees","Greedy","Expected Value","Expected Value","Codeforces","Probability and Expectation","Permutations and Combinations","Problem-Solving Report","Tree DP","Expectation DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Both 数学期望 and 期望 map to “Expected Value” in tags.yaml, so the tag appears twice, matching the Chinese tag list one to one."
---

## C - Serval and Parenthesis Sequence

This problem is mainly about greedy. First, we can establish that the following cases definitely have no solution:

- The first character is ')'; the last character is '('.
- The length of the string is odd.

We notice that in the whole string $s[1 \dots n]$, the first and last characters must be '(' and ')'. So we only need to care about $s[2 \dots n-1]$. Count the number of parentheses that need to be filled in: that is, $(n-2)$ minus the number of parentheses already determined, split into $remL$, the number of left parentheses to fill in, and $remR$, the number of right parentheses to fill in.

<!--more-->

After that we can consider greedy replacement, filling in left parentheses first and then right parentheses. Finally, just check it once.

```cpp
// C.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 3e5 + 2000;
int len, n;
char str[MAX_N];
void goFuck()
{
    printf(":("), exit(0);
}
int main()
{
    scanf("%d", &len), scanf("%s", str), n = len;
    int remL = 0, remR = 0;
    if ((len & 1) || ((len - 2) & 1) || str[0] == ')' || str[len - 1] == '(')
        goFuck();
    str[0] = '(', str[len - 1] = ')';
    len -= 2;
    for (int i = 1; i < n - 1; i++)
        if (str[i] == '(')
            remL++;
        else if (str[i] == ')')
            remR++;
    remL = len / 2 - remL, remR = len / 2 - remR;
    for (int i = 1; i < n - 1; i++)
        if (str[i] == '?' && remL)
            str[i] = '(', remL--;
        else if (str[i] == '?' && remR)
            str[i] = ')', remR--;
    if (remL || remR)
        goFuck();
    int tot = 0;
    for (int i = 0; i < n; i++)
    {
        if (str[i] == '(')
            tot++;
        else
            tot--;
        if (tot == 0 && i != n - 1)
            goFuck();
    }
    if (tot != 0)
        goFuck();
    cout << str;
    return 0;
}
```

## D - Serval and Rooted Tree

A good problem that takes a fair amount of thinking.

This is really just a decision tree, and you're asked to fill numbers in so that the decisions are optimal. We can consider doing a tree DP greedily: let $dp[i]$ be the contribution to the answer, meaning “the number of values larger than the answer”. Then we can do the DP:

$$
dp[u] = \begin{cases} \sum_{i \in son} dp[i], u \in min \\ min_{i \in son} dp[i] \end{cases}, u \in max
$$

Of course, additionally, the values of the leaf nodes are all one. The final answer is $k - dp[1] + 1$.

```cpp
// D.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 3e5 + 2000;
int head[MAX_N], current, n, k, fa[MAX_N], deg[MAX_N], dp[MAX_N];
bool mark[MAX_N];
struct edge
{
    int to, nxt;
} edges[MAX_N << 1];
void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}
void dfs(int u)
{
    if (u != 1 && deg[u] == 1)
    {
        k++, dp[u] = 1;
        return;
    }
    if (mark[u])
        dp[u] = 0x3f3f3f3f;
    else
        dp[u] = 0;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
    {
        dfs(edges[i].to);
        if (mark[u])
            dp[u] = min(dp[u], dp[edges[i].to]);
        else
            dp[u] += dp[edges[i].to];
    }
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &mark[i]);
    for (int i = 2; i <= n; i++)
        scanf("%d", &fa[i]), addpath(fa[i], i), deg[fa[i]]++, deg[i]++;
    dfs(1);
    printf("%d", k - dp[1] + 1);
    return 0;
}
```

## F - Serval and Bonus Problem

This problem is so <span class="slang" data-zh="神仙" data-gloss="shénxiān, “immortal”. Someone, or a problem or idea, so brilliant it seems superhuman.">godlike</span>.

We enumerate the $2n-1$ intervals; the expected length of each interval is $\frac{l}{2n+1}$. In the sense of expectation, we can regard these intervals as having equal length. While enumerating, we can let A be the number of points on the left and B the number of points on the right:

![Annotation 2019-04-15 161610](media/Annotation-2019-04-15-161610.png)

We consider the case where this interval has no points in it. Now we need to compute the probability of this case. The conditions for this case:

1. There are A points on the left and B points on the right.
2. A pairing between k or more points chosen from the A points and k or more points chosen from the B points.
3. The remaining points in A pair up among themselves, and the same goes for B.

Now we can start deriving the formulas. Noticing that pairing within a segment comes up a lot, we define $f(x)$ as “the number of ways for $x$ points to pair up among themselves”:

$$
f(x) = \begin{cases} \prod_{i = 1}^\frac{x}{2} (x - (2i-1)), \text{x is even} \\ 0, \text{x is odd} \end{cases}
$$

Now derive the probability: the probability is just the three cases described above, divided by $f(2n)$:

$$
P(A, B, k) = \frac{ {A \choose k } {B \choose k} k! f(A) f(B) }{f(2n)}
$$

where $k!$ is the number of pairings of these $2k$ chosen points. Now derive the expectation:

$$
\begin{gathered} E(A, B, k) = len * \sum_{i = k}^{min(A,B)} P(A,B,i) \\ E(A, B, k) = \frac{l}{2n+1} * \sum_{i = k}^{min(A,B)} \frac{ {A \choose i } {B \choose i} i! f(A) f(B) }{f(2n)} \end{gathered}
$$

That's it for the derivation; just sum it up.

```cpp
// F.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 5100, mod = 998244353;

ll n, k, l, f[MAX_N << 1], level[MAX_N], level_rev[MAX_N];

ll quick_pow(ll bas, ll tim)
{
    ll ans = 1;
    while (tim)
    {
        if (tim & 1)
            ans = ans * bas % mod;
        bas = bas * bas % mod;
        tim >>= 1;
    }
    return ans;
}

ll comb(ll x, ll y)
{
    return level[x] * level_rev[x - y] % mod * level_rev[y] % mod;
}

int main()
{
    scanf("%d%d%d", &n, &k, &l);
    // Get Ready for the f;
    f[0] = 1;
    for (int i = 1; i <= n; i++)
        f[2 * i] = f[2 * (i - 1)] * (2 * i - 1) % mod;

    // Get ready for the levels;
    level[1] = level[0] = level_rev[1] = level_rev[0] = 1;
    for (int i = 2; i < MAX_N; i++)
        level[i] = level[i - 1] * i % mod;
    level_rev[MAX_N - 1] = quick_pow(level[MAX_N - 1], mod - 2);
    for (int i = MAX_N - 1; i >= 3; i--)
        level_rev[i - 1] = level_rev[i] * i % mod;

    ll answer = 0;

    for (int h = 2; h <= 2 * n; h++)
    {
        int A = h - 1, B = 2 * n - h + 1;
        for (int i = k; i <= min(A, B); i++)
        {
            ll all = comb(A, i) * comb(B, i) % mod * level[i] % mod * f[A - i] % mod * f[B - i] % mod;
            answer = (answer + all) % mod;
        }
    }
    answer = answer * quick_pow(2 * n + 1, mod - 2) % mod * quick_pow(f[2 * n], mod - 2) % mod * l % mod;
    printf("%lld", answer);
    return 0;
}
```
