---
id: 1924
lang: en
translation_of: index.md
source_sha256: 2c738567d00700aad0e6edce75ff2c69c858a9c12bcf38ba8db8020fbc202e3d
title: "Codeforces 1240D: Stack Exterminable Arrays — Solution"
description: "Count from each start with a DP, getting each jump target nxt[i] by swapping maps in an Aho–Corasick-like way instead of brute force."
tags: ["OI","DP","Strings","STL"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "类似于 KMP 的 AC 自动机的方法 rendered as “a method like the Aho–Corasick automaton, which is similar to KMP” (KMP-like AC automaton)."
  - "以i开头向右延伸的答案 kept vague as in the source: “the answer for those starting at i and extending to the right”."
---

## Main Idea

When I first saw the divide-and-conquer tag, I made up my mind to solve it with divide and conquer, but before long I found the information extremely hard to make use of and <span class="slang" data-zh="弃疗" data-gloss="qìliáo, short for 放弃治疗 “give up treatment”. Giving up on something as hopeless.">gave up on it</span>. Let's consider solving this problem with a method like the Aho–Corasick automaton, which is similar to KMP.

First, let $dp[i]$ be the answer for those starting at $i$ and extending to the right; then when we go left we can merge these, and we set $nxt[i]$ to jump with. Since doing the process of getting the $nxt$ array by brute force would make the time complexity <span class="slang" data-zh="GG" data-gloss="Gamer shorthand for “good game”, typed when conceding a match. Here: it is over, I am done for.">GG</span>, we can merge the information with a Map in a way similar to the Aho–Corasick automaton: swap in the Map at position $nxt[i]+1$ and set the current position. Finally, just do the DP.

<!--more-->

## Code

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

using namespace std;

const int MAX_N = 3e5 + 200;

int q, n, ai[MAX_N], nxt[MAX_N], dp[MAX_N];
map<int, int> nxt_map[MAX_N];
ll ans;

int main()
{
    scanf("%d", &q);
    while (q--)
    {
        scanf("%d", &n), ans = 0;
        for (int i = 1; i <= n; i++)
            scanf("%d", &ai[i]);
        for (int i = 1; i <= n + 2; i++)
            nxt[i] = -1, dp[i] = 0, nxt_map[i].clear();
        for (int i = n; i >= 1; i--)
        {
            if (nxt_map[i + 1].count(ai[i]))
            {
                int pos = nxt_map[i + 1][ai[i]];
                if (pos <= n && ai[i] == ai[pos])
                {
                    nxt[i] = pos, swap(nxt_map[i], nxt_map[pos + 1]);
                    if (pos <= n - 1)
                        nxt_map[i][ai[pos + 1]] = pos + 1;
                }
            }
            nxt_map[i][ai[i]] = i;
        }
        for (int i = n; i >= 1; i--)
            if (nxt[i] != -1)
                dp[i] = 1 + dp[nxt[i] + 1], ans += dp[i];
        printf("%lld\n", ans);
    }
    return 0;
}
```
