Maximum beauty subsequences

4.6

7 votes
2D dynamic programming, Algorithms, Dynamic Programming
Problem

A string is said to contain a value that is known as its beauty.

You are given M pairings where the ith pairing is {(ai,bi):ki}. Here, ai and bi are lowercase English letters and ki is a positive integer.

There exists a string S of length L. For the ith pairing, let the number of indices j[1,L1] such that Sj=ai and Sj+1=bi be counti. The beauty of S is the sum of countiki for each i[1,M].

You are given a string A of length N consisting of lowercase English letters. A string can be formed from a subsequence of a string by concatenating the characters of the subsequence in order of occurrence. You are required to find the maximum beauty that can be obtained by selecting any strings that can be formed by a subsequence of A

Input format

  • The first line contains a single integer N that denotes the length of string A.
  • The second line contains string A.
  • The third line contains a single integer M which denotes the number of pairings.
  • The next M lines represent the pairings. Each of these lines contain three space-separated values. The first two are the lowercase English letters ai and bi. The third value is the integer ki.

Output format

Print a single line containing the maximum beauty that can be obtained from a string formed by a subsequence of A.

Constraints

1N21051M1051ki106

Sj, ai, bi are lowercase English letters.

 

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The subsequence A1,A2,A5 forms the string abc. The beauty of this string is 15, which is the maximum that can be obtained. Note that this is not the only subsequence that forms a string with the maximum beauty.

Editor Image

?