---
id: 2576
lang: en
translation_of: index.md
source_sha256: 706fb8e69cfcf481fb85fe8bd77ec61ff4c861f3fd2cbf872362b03037ffb1d2
title: "[Codeforces 461E] Appleman and a Game — Solution"
description: "Binary search on the answer with matrix exponentiation over starting characters; a counting property keeps the trie of substrings shallow."
tags: ["OI","Trie","Counting","Matrix Exponentiation","Floyd","Properties"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "亦而反之 (a nonstandard form of 反之亦然) rendered as “and vice versa”."
  - "本质不同 rendered as “distinct”."
---

## Main Idea

First, setting the original problem aside and considering only the optimal strategy: clearly, the longer the string we can currently match, the better. So we can consider binary searching on the answer: compute the longest string that can be assembled with the current number of appends, then compare it with $n$.

<!--more-->

So how do we compute this thing? We can consider computing a $DP$: let $f[a][b][L]$ be the minimum size when the $L$-th append adds a string whose first character is $a$ and the $L + 1$-th append adds a string beginning with $b$, where these two strings joined together do not occur in the original string. If we ignore the time complexity, this thing can be computed with Floyd. Here, we notice that $L$ is huge but $a, b$ are tiny, so we can try matrix exponentiation.

All we need to compute now is the data for $f[][][1]$. For this data we could consider building a trie, stuffing all the suffixes into it, and then counting by brute force. But that definitely won't work.

However, there is a property we can exploit. Consider computing $g[a][b][L]$, the number of strings in $T$ that start with $a$, end with $b$ and have length $L$ (they need to be distinct). If this count reaches $4^{L - 2}$, then every string at this scale has appeared, so there is no case of a string not appearing; and vice versa.

This leads to a property. Consider the invalid case:

$$
\begin{gathered} |T| \geq g[a][b][L] \geq 4^{L-2} \\ |T|  \geq 4^{L-2} \end{gathered}
$$

This $L$ is surely small, so the trie and the like only need to be on the order of $\Theta(L)$.

## Code

```cpp
// CF461E.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e5 + 200;

typedef long long ll;

int m, ch[MAX_N * 20][4], calc[4][4][20], ptot, mlen;
ll n;
bool tag[MAX_N * 20];
char str[MAX_N];

ll fpow(ll bas, ll tim)
{
    ll ret = 1;
    while (tim)
    {
        if (tim & 1)
            ret *= bas;
        bas *= bas;
        tim >>= 1;
    }
    return ret;
}

struct matrix
{
    ll mat[4][4];
    ll *operator[](const int &rhs) { return mat[rhs]; }
    matrix operator*(const matrix &rhs)
    {
        matrix ret;
        memset(ret.mat, 0x3f, sizeof(ret.mat));
        for (int k = 0; k < 4; k++)
            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++)
                    ret[i][j] = min(ret[i][j], mat[i][k] + rhs.mat[k][j]);
        return ret;
    }
    matrix operator^(const ll &rhs)
    {
        ll tim = rhs - 1;
        matrix ret = *this, bas = *this;
        while (tim)
        {
            if (tim & 1)
                ret = ret * bas;
            bas = bas * bas;
            tim >>= 1;
        }
        return ret;
    }
} trans;

void insert(int start_pos)
{
    int p = 0, sc = str[start_pos] - 'A';
    for (int i = start_pos; i <= min(start_pos + mlen - 1, m); i++)
    {
        int c = str[i] - 'A';
        if (ch[p][c] == 0)
            ch[p][c] = ++ptot;
        p = ch[p][c];
        if (!tag[p])
            tag[p] = true, calc[sc][c][i - start_pos + 1]++;
    }
}

bool check(ll mid)
{
    matrix ret = trans ^ mid;
    bool flag = true;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            flag &= ret[i][j] >= n;
    return flag;
}

int main()
{
    scanf("%lld%s", &n, str + 1), m = strlen(str + 1), mlen = min(11, m + 1);
    for (int i = 1; i <= m; i++)
        insert(i);
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            for (int k = mlen; k >= 2; k--)
                if (calc[i][j][k] != fpow(4, k - 2))
                    trans[i][j] = k - 1;
    ll l = 1, r = n, res = 0;
    while (l <= r)
    {
        ll mid = (l + r) >> 1;
        if (check(mid))
            r = mid - 1, res = mid;
        else
            l = mid + 1;
    }
    printf("%lld\n", res);
    return 0;
}
```
