Codeforces 510C Fox And Names topological sorting
Portal: cf 510D
Given n strings, ask if such an alphabet exists, so that the string can be sorted in the Lexicographic Order. That is, according to the new alphabet, the sorting meets the lexicographic size.
Assuming that the Lexicographic Order is met, we can obtain the relationship between letters based on the existing strings, and then determine whether feasible solutions exist through topological sorting to output arbitrary solutions, therefore, you only need to determine whether a solution exists.
/*************************************** * *************** File Name: a. cpp * Author: kojimai * Create Time: ******************************** * *********************/# include
# Include
# Include
# Include
# Include
Using namespace std; # define FFF 105 char s [FFF] [FFF], ans [30]; int in [FFF]; bool link [26] [26]; queue
P; bool solve () {// determines whether feasible solution int cnt = 0 by means of topological sorting; for (int I = 0; I <26; I ++) {if (in [I] = 0) {p. push (I); ans [cnt ++] = 'A' + I ;}} while (! P. empty () {int now = p. front (); p. pop (); for (int I = 0; I <26; I ++) {if (link [now] [I]) {in [I] --; if (in [I] = 0) {p. push (I); ans [cnt ++] = 'A' + I ;}}} ans [26] = '\ 0'; if (cnt <26) return false; elsereturn true;} int main () {int n; cin> n; for (int I = 0; I <n; I ++) cin> s [I]; bool flag = true; memset (link, false, sizeof (link); memset (in, 0, sizeof (in )); for (int I = 0; I <n-1 & flag; I ++) {bool OK = false; int l1 = Strlen (s [I]), l2 = strlen (s [I + 1]); for (int j = 0; j <l1 & j <l2 &&! OK; j ++) {if (s [I] [j]! = S [I + 1] [j]) {// the size of the Lexicographic Order can be compared if the letters in the same position are different. That is, the relative size of the corresponding letter is OK = true; if (! Link [s [I] [j]-'a'] [s [I + 1] [j]-'a']) {in [s [I + 1] [j]-'a'] ++; link [s [I] [j]-'a'] [s [I + 1] [j]-'a'] = true ;}} if (! OK & l1> l2) flag = false; // if the prefix of a string is identical but the length of the first string is large, the two strings must not meet the Lexicographic Order} if (! Flag) {printf ("Impossible \ n");} else {flag = solve (); if (! Flag) printf ("Impossible \ n"); elseprintf ("% s", ans) ;}return 0 ;}