1 条题解

  • 0
    @ 2026-11-2 12:34:43

    字典序第一(First) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <algorithm>
    #include <iostream>
    #include <queue>
    #include <string>
    #include <vector>
    using namespace std;
    
    struct Node {
        int ch[26];
        bool is_end;
        Node() {
            fill(begin(ch), end(ch), 0);
            is_end = false;
        }
    };
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        if (!(cin >> n)) return 0;
        vector<string> words(n);
        vector<Node> tr;
        tr.reserve(300005);
        tr.emplace_back();
        for (int i = 0; i < n; ++i) {
            cin >> words[i];
            int u = 0;
            for (char ch : words[i]) {
                int c = ch - 'a';
                if (!tr[u].ch[c]) {
                    tr[u].ch[c] = (int)tr.size();
                    tr.emplace_back();
                }
                u = tr[u].ch[c];
            }
            tr[u].is_end = true;
        }
    
        vector<string> ans;
        for (int i = 0; i < n; ++i) {
            const string& s = words[i];
            int u = 0;
            bool prefix_conflict = false;
            int adj[26] = {0};
            for (char ch : s) {
                if (tr[u].is_end) {
                    prefix_conflict = true;
                    break;
                }
                int c = ch - 'a';
                for (int o = 0; o < 26; ++o) {
                    if (o != c && tr[u].ch[o]) {
                        adj[c] |= (1 << o);
                    }
                }
                u = tr[u].ch[c];
            }
            if (prefix_conflict) continue;
    
            int indeg[26] = {0};
            for (int a = 0; a < 26; ++a) {
                for (int b = 0; b < 26; ++b) {
                    if ((adj[a] >> b) & 1) indeg[b]++;
                }
            }
            queue<int> q;
            for (int a = 0; a < 26; ++a) {
                if (indeg[a] == 0) q.push(a);
            }
            int visited = 0;
            while (!q.empty()) {
                int x = q.front();
                q.pop();
                visited++;
                for (int y = 0; y < 26; ++y) {
                    if ((adj[x] >> y) & 1) {
                        if (--indeg[y] == 0) q.push(y);
                    }
                }
            }
            if (visited == 26) ans.push_back(s);
        }
    
        cout << ans.size() << "\n";
        for (const auto& s : ans) cout << s << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    8597
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者