1066. Small m family of cattle description
Little M is a famous manor. Because of recent beef prices, smart small m decided to start raising cattle. In order to keep track of all the cows, little m has installed a set of automatic systems on the manor. He gave each of the cows an electronic grade. When cows walk through this system, the name of the cow will be automatically read into.
The electronic name of each cow is a string of length m, consisting of n different lowercase letters.
Soon, the naughty cows found a loophole in the system: they could walk backwards through the barcode reader. A name of ABCBA will not cause any problems, but a cow named ABCB will become two cows (ABCB and BCBA).
So small m decided to change the name of the cows, so that the name of the cow is read and anti-reading are the same. Small m can add or remove letters at any location. However, there is a fee for adding and removing each letter. For the name of a cow and all the fees for adding or removing letters, find the minimum fee to change the name.
Note: An empty string is also a valid name.
Input Format
First line: Two numbers separated by a space, N and M.
Second line: M characters, the initial name of the ox.
3rd to n+2: Each line contains one letter and two integers, each of which is the cost of adding and removing the letter.
0≤N≤,0≤M≤ ,0≤ 10000
Output Format
An integer that changes the minimum cost for all names.
Sample Input
3 4abcba 1000 1100b 350 700c 200 800
Sample Output
900
==========================================================================================================
开始用的就是简单的递归算法,然后没有通过,最终用动态规划解决了。思想就是从两边开始遍历字符串,通过比较确定添加或删除哪边的字符。
代码如下:
1 //small M family of cows2#include <iostream>3#include <string>4#include <vector>5 using namespacestd;6 7 8 intclist[ -]; 9vector<vector<int> >state;//dynamic planning, recording statusTen stringOri_name; One intn,m; A intCalcost (int,int); - intMain () { - theCin>>n>>m>>Ori_name; - state.resize (M); - for(intI=0; i<m;++i) state.at (i). Resize (m,-1); - + for(intI=0; i<n;++i) { - intAcost,dcost; + Charcha; ACin>>cha>>acost>>Dcost; atclist[cha-'a'] = Acost<dcost?Acost:dcost; - } - intMin_cost = Calcost (0, M-1); -cout<<Min_cost; - - return 0; in } - intCalcost (intLintr) { to intI,tem_cost1,tem_cost2; + CharLeft,right; - the if(L>=R)return 0; * if(Ori_name[l]==ori_name[r])returnCalcost (++l,--R); $ if(State.at (L). at (R) >=0)returnstate.at (L). at (R);Panax Notoginsengleft = Ori_name[l]-'a'; -right = Ori_name[r]-'a'; theTem_cost1 = Clist[left] + calcost (l +1, R); +Tem_cost2 = Clist[right] + calcost (l,r-1); A intMin_cost = Tem_cost1<tem_cost2?Tem_cost1:tem_cost2; theState.at (L). at (r) =Min_cost; + returnMin_cost; -}
View Code
"Shanghai Jiaotong University OJ" Small M home Cow (palindrome string)