lightoj 1033 区间dp

来源:互联网 发布:优化排名工具 编辑:程序博客网 时间:2024/05/01 21:45

By definition palindrome is a string which is not changed when reversed. “MADAM” is a nice example of palindrome. It is an easy job to test whether a given string is a palindrome or not. But it may not be so easy to generate a palindrome.

Here we will make a palindrome generator which will take an input string and return a palindrome. You can easily verify that for a string of length n, no more than (n - 1) characters are required to make it a palindrome. Consider “abcd” and its palindrome “abcdcba” or “abc” and its palindrome “abcba”. But life is not so easy for programmers!! We always want optimal cost. And you have to find the minimum number of characters required to make a given string to a palindrome if you are only allowed to insert characters at any position of the string.

Input
Input starts with an integer T (≤ 200), denoting the number of test cases.

Each case contains a string of lowercase letters denoting the string for which we want to generate a palindrome. You may safely assume that the length of the string will be positive and no more than 100.

Output
For each case, print the case number and the minimum number of characters required to make string to a palindrome.

Sample Input
Output for Sample Input
6
abcd
aaaa
abc
aab
abababaabababa
pqrsabcdpqrs
Case 1: 3
Case 2: 0
Case 3: 2
Case 4: 1
Case 5: 0
Case 6: 9

这个题就是发现了这么几件事
第一个就是回文串是怎么构成的
一定是两边相等
不相等就要补充
那么从里面开始找
dp记录每一个小区间都补成回文串是最小的补充次数
如果两边不相等那么dp[b][a]=min(dp[c+1][a]+c-b+1,dp[b][a]);
dp[b][a]=min(dp[b][c]+a-c,dp[b][a]);
如果相等那么就是
dp[b][a]=dp[b+1][a-1];
里面的所有区间在后续使用的时候可以全部当成回文串来看
因为本题只需要求个数不需要打印字符串

反正还是区间的老套路…
从前向后,从后向前,中间一滚….

#include<iostream>#include<string>#include<algorithm>#include<memory.h>#include<cstdio>using namespace std;int dp[101][101];int main(){    int T;    cin>>T;    int u=0;    string q;    while(T--)    {        cin>>q;        int chang=q.size();        memset(dp,0,sizeof(dp));        for(int a=0;a<q.size();a++)        {            for(int b=a+1;b<q.size();b++)            {                dp[a][b]=0x3f3f3f3f;            }        }        for(int a=0;a<chang;a++)        {            for(int b=a-1;b>=0;b--)            {                if(q[a]==q[b])                {                    dp[b][a]=dp[b+1][a-1];                }                else                {                    for(int c=b;c<a;c++)                    {                        dp[b][a]=min(dp[c+1][a]+c-b+1,dp[b][a]);                        dp[b][a]=min(dp[b][c]+a-c,dp[b][a]);                    }                //  cout<<"b    "<<b<<endl<<"a    "<<a<<endl<<dp[b][a]<<endl;                }            }        }        printf("Case %d: %d\n",++u,dp[0][q.size()-1]);    }    return 0;}
0 0
原创粉丝点击