跳到正文

题解

题解:P11226 [COTS 2019] 排名 Vezuv

rekcA_h约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年2月23日
收录
2026年2月23日
更新
2026年11月16日
篇幅
约 5 分钟
题目
P11226

版本

  1. v2当前
  2. v1

P11226 [COTS 2019] 排名 Vezuv

P11226 [COTS 2019] 排名 Vezuv

思路

思考一下什么情况下一个队伍胜利。容易发现在同一个字符位置,要胜利的字符必须字典序最小。这个东西可以和拓扑序联系到一起,在同一个字符位置,把当前目标字符向其它字符连边,这样可以保证跑一遍拓扑排序后这个字符的拓扑序最小,接着直接输出拓扑序就可以了。如何维护在同一个字符位置,把当前目标字符向其它字符连边这个操作?字典树即可。

再来想什么情况下无解:

  1. 一个字符串有前缀。
  2. 建出来的图有环。

特判一下就可以了。

C++
#include<bits/stdc++.h>
using namespace std;

auto mapping = [](char c) -> int {return c - 'a';};

struct trie{
    int root = 1,tp = 1;
    vector<int> is_end;
    vector<array<int,26>> ch;
    trie(int maxn){
        is_end.resize(maxn + 5);
        ch.resize(maxn + 5);
    }

    void insert(string s){
        int p = 1;
        for(auto c : s){
            int id = mapping(c);
            if(!ch[p][id]) ch[p][id] = ++tp;
            p = ch[p][id];
        }
        is_end[p] = 1;
    }
};

int main(){
    int n;
    cin>>n;
    vector<string> a(n);
    trie t(1e6);
    for(auto &s : a){
        cin>>s;
        t.insert(s);
    }
    for(auto &s : a){
        array<array<int,26>,26> G{};
        int p = 1;
        int pre = 0;
        for(auto c : s){
            if(t.is_end[p]){
                pre = 1;
                break;
            }
            int id = mapping(c);
            for(int i = 0;i < 26;i++){
                if(t.ch[p][i] && i != id){
                    G[id][i]++;
                }
            }
            p = t.ch[p][id];
        }
        if(pre){
            cout<<"nemoguce"<<'\n';
            continue;
        }
        array<int,26> in{};
        for(int i = 0;i < 26;i++){
            for(int j = 0;j < 26;j++){
                if(G[i][j]){
                    in[j]++;
                }
            }
        }
        queue<int> q;
        for(int i = 0;i < 26;i++){
            if(in[i] == 0) q.push(i);
        }
        string ans;
        while(!q.empty()){
            int u = q.front();
            q.pop();
            ans += (char)(u + 'a');
            for(int i = 0;i < 26;i++){
                if(G[u][i]){
                    in[i]--;
                    if(in[i] == 0){
                        q.push(i);
                    }
                }
            }
        }
        if(ans.size() < 26){
            cout<<"nemoguce"<<'\n';
        }
        else{
            cout<<ans<<'\n';
        }
    }
    return 0;
}
原文