4 public class funny_gk
{
6 static PrintWriter out
;
8 static int MAX_N
= 100;
9 static int MAX_M
= 1000;
11 static final int MAX_W
= 100;
12 static final int MIN_CH
= 'A';
13 static final int MAX_CH
= 'Z';
17 static class Entry
implements Comparable
<Entry
> {
19 final List
<Integer
> in
;
21 Entry(String word
, List
<Integer
> in
) {
27 public int compareTo(Entry that
) {
28 return that
.in
.size() - this.in
.size();
32 Queue
<Entry
> queue
= new PriorityQueue
<Entry
>();
33 Set
<String
> queued
= new HashSet
<String
>();
35 private void enqueue(String word
, List
<Integer
> in
) {
36 if (queued
.add(word
)) {
39 queue
.add(new Entry(word
, in
));
44 private List
<Integer
> count(String word
, List
<Integer
> in
) {
45 int[] letters
= letters(word
);
46 List
<Integer
> result
= new ArrayList
<Integer
>();
47 for (Integer i
: in
) {
48 if (match(letters
, letterss
.get(i
))) {
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
]++;
73 Set
<String
> solve(int n
, Set
<String
> words
) {
74 letterss
= new ArrayList
<int[]>();
75 for (String word
: words
) {
76 letterss
.add(letters(word
));
79 List
<Integer
> all
= new ArrayList
<Integer
>();
80 for (int i
= 0; i
< words
.size(); i
++) {
85 Set
<String
> result
= new TreeSet
<String
>();
87 while (!queue
.isEmpty() && result
.size() < n
) {
88 Entry entry
= queue
.remove();
89 String word
= entry
.word
;
90 if (word
.length() > 0 && !words
.contains(word
)) {
95 for (int i
= 0; i
< 26; i
++) {
96 enqueue(word
+ (char) ('A' + i
), entry
.in
);
100 StringBuilder sb
= new StringBuilder();
101 for (int i
= 0; result
.size() < n
; i
++) {
103 String word
= sb
.toString();
104 if (!words
.contains(word
)) {
111 public void run() throws IOException
{
112 int n
= in
.nextInt();
113 int m
= in
.nextInt();
115 assert 1 <= n
&& n
<= MAX_N
;
116 assert 1 <= m
&& m
<= MAX_M
;
118 Set
<String
> words
= new HashSet
<String
>();
119 for (int i
= 0; i
< m
; i
++) {
120 String word
= in
.next();
123 assert 1 <= word
.length() && word
.length() <= MAX_W
;
124 for (char ch
: word
.toCharArray()) {
125 assert MIN_CH
<= ch
&& ch
<= MAX_CH
;
128 assert !in
.hasNext();
130 Set
<String
> result
= solve(n
, words
);
132 for (String word
: result
) {
137 public static void main(String
[] args
) throws Exception
{
138 in
= new Scanner(new File("funny.in"));
139 out
= new PrintWriter("funny.out");
141 new funny_gk().run();