[Ultraviolet A] 10739-string to palindrome (Dynamic Planning)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.