Home BOJ. Phone Keyboard (5670)
Post
Cancel

BOJ. Phone Keyboard (5670)

[Link] https://www.acmicpc.net/problem/5670


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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		Trie trie;
		ArrayList<String> al = new ArrayList<>();
		while(true) {
			String ss = br.readLine();
			if(ss == null || ss.length() == 0) break;
			int n = toi(ss);
			if(n == 0) break;
			trie = new Trie();
			al.clear();

			for(int i = 0; i < n; i++) {
				String s = br.readLine();
				trie.add(s);
				al.add(s);
			}
			int count = 0;
			for(String s: al) {
				count += trie.solve(s);
			}
			sb.append(String.format("%.2f", (double)count / n)).append("\n");
		}
		print(sb);
	}

	static class Trie {
		Trie[] arr = new Trie[26];
		int num = 0;
		boolean tail;

		void add(String s) {
			int l = s.length();
			Trie t = this;
			for(int i = 0; i < l; i++) {
				int ch = s.charAt(i) - 'a';
				if(t.arr[ch] == null) {
					t.arr[ch] = new Trie();
					t.num++;
				}
				t = t.arr[ch];
			}
			t.tail = true;
		}

		int solve(String s) {
			Trie t = arr[s.charAt(0) - 'a'];
			int cnt = 1;

			for(int i = 1; i < s.length(); i++) {
				if(t.num + (t.tail ? 1 : 0) > 1) cnt++;
				t = t.arr[s.charAt(i) - 'a'];
			}
			return cnt;
		}
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.