Sara has a main string and a list of N available substrings, each with an associated cost. Her goal is to construct the main string by concatenating some of the available substrings, aiming for the minimum possible total cost.
The rules are as follows:
Your task is to help Sara find the minimum cost to construct the entire main string. If it's impossible to form the main string with the given substrings, you should report it.
The first line contains an integer N, the number of available substrings.
The next N lines each contain a substring and its cost, separated by a space.
The final line contains the main string.
Print a single integer representing the minimum cost.
If it is impossible to form the main string, print "Impossible".
This problem can be solved efficiently using dynamic programming. Let dp[i] be the minimum cost to form the prefix of the main string of length i. The goal is to compute dp[length of main string].
10
evi 8
vta 9
co 1
dev 5
vit 6
odv 2
d 3
de 4
itaa 1
a 7
codevita
18
The optimal way to form "codevita" is by using the substrings:
co (cost 1) -> forms "co"
de (cost 4) -> forms "code"
vit (cost 6) -> forms "codevit"
a (cost 7) -> forms "codevita"
Total cost = 1 + 4 + 6 + 7 = 18.
The expected time complexity is O(N^3).
1 <= length of main string <= 50
1 <= N <= 100
1 <= cost of each substring <= 100
length of each substring <= length of main string
All strings consist of lowercase English letters.
Time limit: 1 sec