---
id: 1788
lang: en
translation_of: index.md
source_sha256: 280182f265c7418d383d26f9142e7ecd05c915a9edad99030fd260fcf1128982
title: "P3615: Toilet Plan — Solution"
description: "Take suffix sums with women as -1 and men as +1; it is enough to keep every suffix sum greater than -2."
tags: []
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 如厕计划 rendered literally as “Toilet Plan”."
  - "The closing line (高度相似，太菜了 has no closing parenthesis in the original; kept unclosed. 高度相似 (“highly similar”) does not say to what; rendered literally."
---

## Main Idea

I really should think harder more often; I might well have been able to come up with it.

Consider taking suffix sums over this sequence, with a woman counting as -1 and a man as +1, and you find that it is enough to keep the suffix sum always greater than $-2$. So we can maintain the suffix sum of each segment, and then maintain the maximum suffix sum.

When computing the answer, we need to know how much to raise the polyline so that it never touches the line at $-2$; just find the largest amount of raising (that way everything is valid).

<!--more-->

## Code

```cpp
// P3615.cpp
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAX_N = 200100;

ll n, m, ki[MAX_N], prefix[MAX_N], mx_prefix[MAX_N], acc, ans;
char str[MAX_N];

int main()
{
    scanf("%lld%lld", &n, &m);
    for (int i = 1; i <= m; i++)
    {
        scanf("%s%lld", str + 1, &ki[i]);
        int len = strlen(str + 1);
        for (int j = len; j >= 1; j--)
            prefix[i] += (str[j] == 'F' ? -1 : 1), mx_prefix[i] = max(mx_prefix[i], prefix[i]);
        acc += prefix[i] * ki[i];
    }
    if (acc > 0)
        printf("-1"), exit(0);
    ans = 1, acc = 0;
    for (int i = m; i >= 1; i--)
    {
        if (prefix[i] > 0)
            ans = max(ans, acc + (ki[i] - 1) * prefix[i] + mx_prefix[i]);
        else
            ans = max(ans, acc + mx_prefix[i]);
        acc += prefix[i] * ki[i];
    }
    printf("%lld", ans - 1);
    return 0;
}
```

(Highly similar, I'm way too <span class="slang" data-zh="菜" data-gloss="cài, “vegetable”. Slang for being bad at something; weak.">weak</span>
