Dynamic Comparison Planning
DP [I] [J] convert the original string I ~ Minimum number of operations required to convert a character within J to a return character
The Delete and add operations are essentially the same.
Three state transition equations:
DP [I] [J] = min (DP [I] [J], DP [I + 1] [J]);
DP [I] [J] = min (DP [I] [J], DP [I + 1] [J-1]);
DP [I] [J] = min (DP [I] [J], DP [I] [J-1]);
If I = j dp [I] [J] = 0;
| 14145138 |
10651 |
Pebble Solitaire |
Accepted |
C ++ |
0.009 |
2014-09-04 09:09:42 |
#include<cstdio>#include<algorithm>#include<string>#include<cstring>#include<map>#include<iostream>using namespace std;#define MAXD 1000 + 10#define INF 10000char str[MAXD];int dp[MAXD][MAXD];int dfs(int start,int last){ if(dp[start][last] != -1) return dp[start][last]; if(start == last) return dp[start][last] = 0; if(str[start] == str[last]){ if(start + 1 == last) return dp[start][last] = 0; else return dp[start][last] = dfs(start + 1 , last - 1); } dp[start][last] = INF; if(last - 1 >= start) dp[start][last] = min(dp[start][last],dfs(start,last - 1) + 1); if(start + 1 <= last) dp[start][last] = min(dp[start][last],dfs(start + 1, last) + 1); if(start + 1 <= last - 1) dp[start][last] = min(dp[start][last],dfs(start + 1,last - 1) + 1); return dp[start][last];}int main(){ int T; scanf("%d",&T); for(int Case = 1; Case <= T; Case ++){ scanf("%s",str); memset(dp,-1,sizeof(dp)); int ans = dfs(0,strlen(str) - 1); printf("Case %d: %d\n",Case,ans); } return 0;}
[Ultraviolet A] 10739-string to palindrome (Dynamic Planning)