codeforces 510 C. Fox And Names
http://codeforces.com/contest/510/problem/C
题意:给定n个字符串。问是否存在一种字母顺序,使得这n个字符串的顺序满足字典序(自定义的)。如果有多种顺序,输出字典序(标准的)最小的。
思路:将字符串的关系处理成边的关系。每次对于第i个和第i+1个字符串,从前往后扫,直到不相等的那一位,设为k,然后连边,指向i+1。表明第i个字符串的第k位大于第i+1个字符串的第k位。如果没有不想等的。说明其中一个是另一个的字串。如果前者是后者的字串,那么不影响。如果后者是前者的字串,则不存在满足条件的字典序。然后做拓扑排序。由于有多种输出字典序(标准的)最小的方案。所以存点的时候用优先队列存。
1/* ***********************************************
2Author :111qqz
3Created Time :2015年12月06日 星期日 15时16分50秒
4File Name :code/cf/problem/510C.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25
26
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=105;
34int n;
35char st[N][N];
36int p[30];
37int offset[30];
38bool conc[30][30];
39int in[N];
40int ans[N];
41struct node
42{
43 int x;
44 node(int xx)
45 {
46 x=xx;
47 }
48 bool operator <(const node a)const{
49 return x>a.x;
50 }
51};
52bool getconc( int x,int y)
53{
54 int lx = strlen(st[x]);
55 int ly = strlen(st[y]);
56 int len = min(lx,ly);
57 for ( int i = 0; i < len ; i++)
58 {
59 if (st[x][i]!=st[y][i])
60 {
61 conc[st[x][i]-'a'][st[y][i]-'a'] = true;
62 return true;
63 }
64 }
65 // if (lx>ly) return false;
66 return true;
67}
68bool pre()
69{
70 ms(conc,false);
71 ms(in,0);
72 scanf("%d",&n);
73 for ( int i = 0 ;i < n ; i++) scanf("%s",st[i]);
74
75 bool ok = true;
76 for ( int i = 0 ; i < n-1 ; i++)
77 {
78 ok = getconc(i,i+1);
79 if (!ok) break;
80 }
81 if (ok) return true;
82 return false;
83}
84
85bool topo()
86{
87 priority_queue<node>q;
88 for ( int i = 0 ; i < 26 ; i++)
89 if (in[i]==0) q.push(i);
90
91 int cnt = 0 ;
92
93 while (!q.empty())
94 {
95 node v = q.top();q.pop();
96 cnt++;
97 ans[cnt]=v.x;
98 for ( int i = 0 ; i < 26 ; i++)
99 {
100 if (!conc[v.x][i]) continue;
101 in[i]--;
102 if (in[i]==0) q.push(i);
103 }
104 }
105 if (cnt<26) return false;
106 return true;
107}
108int main()
109{
110 #ifndef ONLINE_JUDGE
111 freopen("code/in.txt","r",stdin);
112 #endif
113 if (pre())
114 {
115 for ( int i = 0 ; i < 26 ; i++)
116 for ( int j = 0 ; j < 26 ; j++)
117 if (conc[i][j]) in[j]++;
118 if (topo())
119 {
120 for (int i = 1 ; i <= 26 ; i++)
121 printf("%c",char(ans[i]+'a'));
122 puts("");
123 }
124 else
125 {
126 puts("Impossible");
127 }
128 }
129 else
130 {
131 puts("Impossible");
132 }
133
134
135 #ifndef ONLINE_JUDGE
136 fclose(stdin);
137 #endif
138 return 0;
139}