forked from improper4/uva
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UVa00200_RareOrder.java
83 lines (68 loc) · 1.87 KB
/
UVa00200_RareOrder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package uva;
/* USER: 46724 (sfmunera) */
/* PROBLEM: 136 (200 - Rare Order) */
/* SUBMISSION: 09367427 */
/* SUBMISSION TIME: 2011-10-13 17:57:58 */
/* LANGUAGE: 2 */
import java.util.*;
import java.io.*;
public class UVa00200_RareOrder {
static boolean[][] adj;
static boolean[] vertices;
static boolean[] visited;
static String sort;
static void dfs(int s) {
visited[s] = true;
for (int i = 0; i < 26; ++i)
if (adj[s][i] && !visited[i])
dfs(i);
sort = (char)(s + 'A') + sort;
}
static void topsort() {
visited = new boolean[26];
sort = "";
for (int i = 0; i < 26; ++i)
if (vertices[i] && !visited[i])
dfs(i);
System.out.println(sort);
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
List<String> dict = new ArrayList<String>();
vertices = new boolean[26];
adj = new boolean[26][26];
int maxlen = 0;
while (true) {
String line = in.readLine();
if (line.equals("#"))
break;
dict.add(line);
maxlen = Math.max(maxlen, line.length());
}
for (int i = 0; i < maxlen; ++i)
for (int j = 0; j < dict.size(); ++j) {
String s = dict.get(j);
if (i >= s.length())
continue;
vertices[s.charAt(i) - 'A'] = true;
if (j > 0) {
String prev = dict.get(j - 1);
if (prev.length() > i) {
if (i == 0 && s.charAt(i) != prev.charAt(i))
adj[prev.charAt(i) - 'A'][s.charAt(i) - 'A'] = true;
else if (s.charAt(i) != prev.charAt(i)) {
boolean ok = true;
for (int k = 0; k < i && ok; ++k)
if (s.charAt(k) != prev.charAt(k))
ok = false;
if (ok)
adj[prev.charAt(i) - 'A'][s.charAt(i) - 'A'] = true;
}
}
}
}
topsort();
in.close();
System.exit(0);
}
}