You have multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i.
For example, a multiset of strings {"abc", "aba", "adc", "ada"} are not easy to remember. And multiset {"abc", "ada", "ssa"} is easy to remember because:
- the first string is the only string that has character c in position 3;
- the second string is the only string that has character d in position 2;
- the third string is the only string that has character s in position 2.
You want to change your multiset a little so that it is easy to remember. For aijcoins, you can change character in the j-th position of the i-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember.
Input
The first line contains two integers n, m (1 ≤ n, m ≤ 20) — the number of strings in the multiset and the length of the strings respectively. Next n lines contain the strings of the multiset, consisting only of lowercase English letters, each string's length is m.
Next n lines contain m integers each, the i-th of them contains integers ai1, ai2, ..., aim (0 ≤ aij ≤ 106).
Output
Print a single number — the answer to the problem.
Example
4 5 abcde abcde abcde abcde 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
3
4 3 abc aba adc ada 10 10 10 10 1 10 10 10 10 10 1 10
2
3 3 abc ada ssa 1 1 1 1 1 1 1 1 1
0
第一次写状压dp。状压dp一般是n比较小的情况,这样可以用n位二进制数表示一个状态,依次来进行动态规划。
对于本题,用col[i][j]表示为了使第i行符合,将第j列中所有与第i行相同的(除了最大的,且可能包括第i行)改成不同的数(n<=20 有26个字母,一定可以)所花费的价格。st[i][j]表示按上述操作后必定符合题意要求的行用二进制表示的状态。
用dp[i]表示状态i下最小的花费(i范围为[0,(1<<n)-1])
由为使第i行可行,可能通过只修改其第j列,也可能按上述方式修改第j列的其他行,来进行递推即可。
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include