[Codeforces]510C. Fox And Names

題目連結:http://codeforces.com/contest/510/problem/C

先比較字串,對字元間的大小關係建一張圖,如果'a' < 'b'那'a'就連一條邊給'b'。
接著就找該圖的拓墣排序即可。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <bitset>
#include <queue>
#include <vector>
#define lld long long
#define PB push_back
#define F first
#define S second
#define jizz cin.tie(0);ios_base::sync_with_stdio(0);
#define endl '\n'
using namespace std;
typedef pair<int,int> Pair;
string s[105],ans;
bitset<30> g[30];
int in[30];
bool topu(){
    queue<int> q;
    for(int i = 0 ; i < 26 ; i++)if(!in[i])q.push(i),ans+='a'+i;
    while(!q.empty()){
        int t = q.front();q.pop();
        for(int i = 0 ; i < 26 ; i++){
            if(g[t][i] && (--in[i]) == 0){
                q.push(i),ans += 'a'+i;
            }
        }
    }
    return ans.length() != 26 ? 0 : 1;
}
int main(){jizz
    int n;cin >> n;
    for(int i = 0 ; i < n ; i++)
        cin >> s[i];
    for(int i = 1 ; i < n ; i++){
        int l = min(s[i-1].length(),s[i].length());
        for(int j = 0 ; j < l ; j++){
            if(s[i][j] != s[i-1][j]){
                if(!g[s[i-1][j]-'a'][s[i][j]-'a']){
                    g[s[i-1][j]-'a'][s[i][j]-'a'] = 1;
                    in[s[i][j]-'a']++;
                }
                goto nutella;
            }
        }
        if(s[i-1].length() > s[i].length())
            return cout << "Impossible" << endl,0;
        nutella:{}
    }
    topu() ? cout << ans << endl : cout << "Impossible" <<endl;
    return 0;
}

留言

這個網誌中的熱門文章

[TIOJ]1617. [Interactive] 中位數

[TIOJ]1337. 隕石

[TIOJ]1994. 冰塊線