1 /* Only sub words of the given words are used. */
5 public class funny_gk_wa_no_generated
{
7 static PrintWriter out
;
9 static int MAX_N
= 100;
10 static int MAX_M
= 1000;
12 static final int MAX_W
= 100;
13 static final int MIN_CH
= 'A';
14 static final int MAX_CH
= 'Z';
18 static class Entry
implements Comparable
<Entry
> {
22 Entry(int count
, String word
) {
28 public int compareTo(Entry that
) {
29 return that
.count
- this.count
;
33 Queue
<Entry
> queue
= new PriorityQueue
<Entry
>();
34 Set
<String
> queued
= new HashSet
<String
>();
36 private void enqueue(String word
) {
37 if (queued
.add(word
)) {
38 int count
= count(word
);
40 queue
.add(new Entry(count
, word
));
45 private int count(String word
) {
46 int[] letters
= letters(word
);
48 for (int[] wordLetters
: letterss
) {
49 if (match(letters
, wordLetters
)) {
56 private boolean match(int[] letters
, int[] wordLetters
) {
57 for (int i
= 0; i
< 26; i
++) {
58 if (letters
[i
] > wordLetters
[i
]) {
65 private int[] letters(String word
) {
66 int[] letters
= new int[26];
67 for (char ch
: word
.toCharArray()) {
68 letters
[ch
- MIN_CH
]++;
75 Set
<String
> solve(int n
, Set
<String
> words
) {
76 letterss
= new ArrayList
<int[]>();
77 for (String word
: words
) {
78 letterss
.add(letters(word
));
82 Set
<String
> result
= new TreeSet
<String
>();
83 while (!queue
.isEmpty() && result
.size() < n
) {
84 String word
= queue
.remove().word
;
85 if (word
.length() > 0 && !words
.contains(word
)) {
90 for (int i
= 0; i
< 26; i
++) {
91 enqueue(word
+ (char) ('A' + i
));
98 public void run() throws IOException
{
100 int m
= in
.nextInt();
102 assert 1 <= n
&& n
<= MAX_N
;
103 assert 1 <= m
&& m
<= MAX_M
;
105 Set
<String
> words
= new HashSet
<String
>();
106 for (int i
= 0; i
< m
; i
++) {
107 String word
= in
.next();
110 assert 1 <= word
.length() && word
.length() <= MAX_W
;
111 for (char ch
: word
.toCharArray()) {
112 assert MIN_CH
<= ch
&& ch
<= MAX_CH
;
115 assert !in
.hasNext();
117 Set
<String
> result
= solve(n
, words
);
119 for (String word
: result
) {
124 public static void main(String
[] args
) throws Exception
{
125 in
= new Scanner(new File("funny.in"));
126 out
= new PrintWriter("funny.out");
128 new funny_gk_wa_no_generated().run();