题意:字串S长M,由N个小写字母构成。欲通过增删字母将其变为回文串,增删特定字母花费不同,求最小花费。
析:是一个简单DP,dp[i][j] 表示区间 i - j 是回文串的最小花费,很容易知道,删除和添加效果是一样的,所以我们就可以只取一个最小值就好。
做的时候我的初始化在外面,就一直WA。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 2e3 + 10; const int mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int dp[maxn][maxn]; char s[maxn]; map<char, int> mp; int main(){ while(scanf("%d %d", &m, &n) == 2){ scanf("%s", s); char op[5]; for(int i = 0; i < m; ++i){ int x, y; scanf("%s %d %d", op, &x, &y); mp[op[0]] = min(x, y); } memset(dp, 0, sizeof dp); for(int l = 1; l < n; ++l){ for(int i = 0; i + l < n; ++i){ int j = i + l; dp[i][j] = INF; if(s[i] == s[j]){ dp[i][j] = dp[i+1][j-1]; continue; } dp[i][j] = min(dp[i][j], dp[i+1][j] + mp[s[i]]); dp[i][j] = min(dp[i][j], dp[i][j-1] + mp[s[j]]); } } printf("%d ", dp[0][n-1]); } return 0; }