行目 には、条件を満たす書き方のうち脊椎に書く文字列が であるものが存在するならば Yes を、存在しないならば No を出力せよ。
1.1. 例
入力例
5
5 3
5 2
4 1
5 1
3 2
8
retro
chris
itchy
tuna
crab
rock
cod
ash
出力例
Yes
Yes
No
No
No
No
No
No
2. ハッシュテーブルで記録した
背骨となる単語を一つ選んだときに、1文字目から順にほかの単語で作れるか、を調べることにします。
すると、必要なのは b 文字目に必要な文字があるか、ということになります。 これは単語リストによって決まるので、あらかじめハッシュテーブルに三つ組を記録しておきます。
;; Make hash-table, key (a b ch);; to consult whether the word whose length is a has letter ch on b ;; usage: (gethash '(5 3 #\r) (char-table words))
(defun char-table (words)
(declare (type list words))
(let ((table (make-hash-table:test #'equal)))
(loop for w in words do
(loop for ch across w
for b from 1
with a = (length w)
do (setf (gethash (list a b ch) table) t))
finally (return table))))Code language:Lisp(lisp)
キーの同一性は、equalで検査すれば、三つ組の中身を含めてチェックできます。
そうすれば、あとは1文字目から順に利用可能かどうかをチェックするだけです。
;; check whether the word can be constructed by char table.
(defun can-construct-p (the-word n ab-s ch-table)
(cond ((/= n (length the-word)) nil)
((loop for ab in ab-s
for i from 0
always (gethash
(list (car ab)
(cadr ab)
(aref the-word i))
ch-table)) t)))Code language:Lisp(lisp)
2.1. 完成したコード
;; The words need to be collected by read-line.
(defun solve ()
(let* ((n (read))
(ab-s (loop repeat n collect (list (read) (read))))
(m (read))
(words (loop repeat m collect (read-line)))
(ch-table (char-table words)))
(loop for w in words do
(princ (if (can-construct-p w n ab-s ch-table)
"Yes""No"))
(princ #\newline))))
;; Make hash-table, key (a b ch);; to consult whether the word whose length is a has letter ch on b ;; usage: (gethash '(5 3 #\r) (char-table words))
(defun char-table (words)
(declare (type list words))
(let ((table (make-hash-table:test #'equal)))
(loop for w in words do
(loop for ch across w
for b from 1
with a = (length w)
do (setf (gethash (list a b ch) table) t))
finally (return table))))
;; check whether the word can be constructed by char table.
(defun can-construct-p (the-word n ab-s ch-table)
(cond ((/= n (length the-word)) nil)
((loop for ab in ab-s
for i from 0
always (gethash
(list (car ab)
(cadr ab)
(aref the-word i))
ch-table)) t)))
#-swank
(solve)
Code language:Lisp(lisp)