forked from nanwan03/poj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2418 Hardwood Species - Trie.java
58 lines (55 loc) · 1.37 KB
/
2418 Hardwood Species - Trie.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
import java.io.*;
import java.util.*;
import java.math.*;
class TrieNode {
TreeMap<Character, TrieNode> map = new TreeMap<Character, TrieNode>();
int count = 0;
TrieNode() {
}
public TrieNode next(char c) {
return map.get(c);
}
public boolean contains(char c) {
return map.containsKey(c);
}
public void insert(char c) {
if (!contains(c)) {
map.put(c, new TrieNode());
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String name;
int total = 0;
TrieNode trie = new TrieNode();
while ((name = cin.readLine()) != null) {
insert(trie, name.toCharArray());
total++;
}
dfs(trie, total, new StringBuilder());
}
private static void insert(TrieNode root, char[] chars) {
for (char c : chars) {
root.insert(c);
root = root.next(c);
}
root.count++;
}
private static void dfs(TrieNode root, int total, StringBuilder str) {
if (root == null) {
return;
}
if (root.count != 0) {
System.out.printf("%s %.4f\n", str.toString(), root.count * 100.0 / total);
}
Iterator<Map.Entry<Character, TrieNode>> it = root.map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Character, TrieNode> entry = it.next();
str.append(entry.getKey());
dfs(entry.getValue(), total, str);
str.deleteCharAt(str.length() - 1);
}
}
}