input: from typing import List
  from random import randint
  from collections import defaultdict
  from math import inf
  
  def min_expense_to_form_str(target: str, words: List[str], costs: List[int]) -> int:
      """
      Given a string target, a list of strings words, and a list of integers costs of the same length,
      compute the minimal cost to construct the string target using any concatenation of the strings from words,
      where the cost to use words[i] is costs[i]. If it is impossible to form target, return -1.
  
      Examples:
      >>> target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]
      7
      >>> target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]
      -1
  
      Constraints:
      1 <= target.length <= 5 * 10^4
      1 <= words.length == costs.length <= 5 * 10^4
      1 <= words[i].length <= target.length
      The total sum of words[i].length is at most 5 * 10^4.
      target and words[i] consist only of lowercase English letters.
      1 <= costs[i] <= 10^4
      """
output:     
      dp = [inf] * (len(target) + 1)
      dp[0] = 0
  
      for i in range(1, len(target) + 1):
          for j, word in enumerate(words):
              if i >= len(word) and target[i - len(word):i] == word:
                  dp[i] = min(dp[i], dp[i - len(word)] + costs[j])
  
      return dp[len(target)] if dp[len(target)] != inf else -1
  