ARC081E

· · 题解

题目链接

思路:

先定义一个数组 nxt_{i,j},表示从 i 开始字符 j 第一次出现的位置。

接着进行 bfs,扫到的第一个 nxt_{i,j}=0 就是第一个未出现的字符串。

在 bfs 时需要记录每个位置的上一个,找到答案时倒序输出即可(记得判重)。

总时间复杂度 O(n)。

#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
char ch[N], ans[N];
int n, nxt[N][26], pre[N], cnt;
bool vs[N];
int main() {
    cin >> (ch + 1);
    n = strlen(ch + 1);
    for (int i = n; i; i--) {
        for (int j = 0; j < 26; j++)
            nxt[i][j] = nxt[i + 1][j];
        nxt[i][ch[i] - 'a'] = i;
    }//预处理
    queue<int>q;
    vs[0] = 1;
    q.push(0);
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        for (int i = 0; i < 26; i++) {
            int t = nxt[x + 1][i];
            if (!t) {//第一个未被找到的字符串
                ans[++cnt] = 'a' + i;
                while (x) {
                    ans[++cnt] = ch[x];
                    x = pre[x];
                }
                for (int i = cnt; i; i--)
                    cout << ans[i];
                return 0;
            } else if (vs[t])
                continue;
            pre[t] = x, vs[t] = 1;
            q.push(t);
        }
    }
    return 0;
}