Cipher
Шифр
Statement
A string S of length N (0 ≤ N ≤ 100) and a dictionary of M words (0 ≤ M ≤ 100) are given, all made of lowercase letters a–z, with no dictionary word longer than S. Find the minimum number of characters to delete from S so that the remaining string can be written as a concatenation of dictionary words, each usable any number of times (the empty string counts as a valid concatenation of zero words).
In the sample, deleting the letters f and t from abafchtdsya gives
abachdsya, which splits into the words a, bach, dsy, a.
Input / Output
Input file CIPHER.DAT starts with a line containing two integers N and M,
followed by the string S on the next line, followed by M lines each holding
one dictionary word. Output file CIPHER.SOL must contain a single natural
number: the minimum number of deletions required.
Constraints
0 ≤ N ≤ 100, 0 ≤ M ≤ 100, dictionary word length ≤ N, alphabet is a–z only.
Example
Input:
11 5
abafchtdsya
aba
a
bach
dsy
zero
Output:
2
Solution idea
Build a weighted DAG over the N+1 gaps between characters of S: a default edge from position i to i+1 with weight 1 represents deleting character i, and for every occurrence of a dictionary word as a subsequence of some span S[i+1..j], add an edge from i to j whose weight is the number of characters in that span skipped over by the match (i.e. the extra deletions needed to isolate the word). The answer is then the shortest path from position 0 to position N in this DAG, which the reference solution computes with a Dijkstra-style relaxation after precomputing, for each dictionary word, all its subsequence occurrences and their skip counts.