1 /* skips prefixes equals to some word. */
6 public class funny_gk_wa_skip_words
{
8 static PrintWriter out
;
10 static int MAX_N
= 100;
11 static int MAX_M
= 1000;
13 static final int MAX_W
= 100;
14 static final int MIN_CH
= 'A';
15 static final int MAX_CH
= 'Z';
19 static class Entry
implements Comparable
<Entry
> {
23 Entry(int count
, String word
) {
29 public int compareTo(Entry that
) {
30 return that
.count
- this.count
;
34 Queue
<Entry
> queue
= new PriorityQueue
<Entry
>();
35 Set
<String
> queued
= new HashSet
<String
>();
38 private void enqueue(String word
) {
39 System
.out
.println(word
);
40 if (queued
.add(word
) && !words
.contains(word
)) {
41 int count
= count(word
);
43 queue
.add(new Entry(count
, word
));
48 private int count(String word
) {
49 int[] letters
= letters(word
);
51 for (int[] wordLetters
: letterss
) {
52 if (match(letters
, wordLetters
)) {
59 private boolean match(int[] letters
, int[] wordLetters
) {
60 for (int i
= 0; i
< 26; i
++) {
61 if (letters
[i
] > wordLetters
[i
]) {
68 private int[] letters(String word
) {
69 int[] letters
= new int[26];
70 for (char ch
: word
.toCharArray()) {
71 letters
[ch
- MIN_CH
]++;
78 Set
<String
> solve(int n
, Set
<String
> words
) {
80 letterss
= new ArrayList
<int[]>();
81 for (String word
: words
) {
82 letterss
.add(letters(word
));
86 Set
<String
> result
= new TreeSet
<String
>();
87 while (!queue
.isEmpty() && result
.size() < n
) {
88 String word
= queue
.remove().word
;
89 if (word
.length() > 0 && !words
.contains(word
)) {
94 for (int i
= 0; i
< 26; i
++) {
95 enqueue(word
+ (char) ('A' + i
));
99 System
.out
.println(result
.size());
101 StringBuilder sb
= new StringBuilder();
102 for (int i
= 0; result
.size() < n
; i
++) {
104 String word
= sb
.toString();
105 if (!words
.contains(word
)) {
112 public void run() throws IOException
{
113 int n
= in
.nextInt();
114 int m
= in
.nextInt();
116 assert 1 <= n
&& n
<= MAX_N
;
117 assert 1 <= m
&& m
<= MAX_M
;
119 Set
<String
> words
= new HashSet
<String
>();
120 for (int i
= 0; i
< m
; i
++) {
121 String word
= in
.next();
124 assert 1 <= word
.length() && word
.length() <= MAX_W
;
125 for (char ch
: word
.toCharArray()) {
126 assert MIN_CH
<= ch
&& ch
<= MAX_CH
;
129 assert !in
.hasNext();
131 Set
<String
> result
= solve(n
, words
);
133 for (String word
: result
) {
138 public static void main(String
[] args
) throws Exception
{
139 in
= new Scanner(new File("funny.in"));
140 out
= new PrintWriter("funny.out");
142 new funny_gk_wa_skip_words().run();