Portal: CF 510D
Given n strings, ask if such an alphabet exists, so that the ordering of strings satisfies the dictionary order. That is, according to the new alphabet, the ordering satisfies the dictionary order size.
Assuming that the dictionary order is satisfied, we can derive the size relationship between the letters according to the existing string, and then use the topological sort to determine if there is a viable solution and output any solution, so we just need to determine if there is a solution.
/****************************************************** * File name:a.cpp * Author:kojimai * Create time:2015 February 03 Tuesday 00:32 13 sec ******************************************************/#include <cstdio> #include < cstring> #include <cmath> #include <algorithm> #include <iostream> #include <queue> using
namespace Std;
#define FFF, Char s[fff][fff],ans[30];
int IN[FFF];
BOOL Link[26][26];
Queue<int> p;
BOOL Solve () {//by topological sorting to determine if there is a viable solution int cnt = 0;
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] = ' + ';
if (CNT <) return false;
else return 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 letters in the same position are different, the size of the dictionary order can be compared
, i.e. 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;//One of the two string prefixes is identical, but the first string is a large length, then the two strings must not satisfy the dictionary order} if (!flag) {p
rintf ("impossible\n");
} else {flag = solve ();
if (!flag) printf ("impossible\n");
else printf ("%s", ans);
} return 0;
}