D - Palindrome Partitioning
来源:互联网 发布:抓包8888端口干嘛的 编辑:程序博客网 时间:2024/06/04 20:02
这题我用了很笨的方法,可是经过一番努力我还是搞定了,很激动很激动
用一维数组记录从第一个字符到该位置最少回文串个数
Description
A palindrome partition is the partitioning of a string such that each separate substring is a palindrome.
For example, the string "ABACABA" could be partitioned in several different ways, such as {"A","B","A","C","A","B","A"}, {"A","BACAB","A"}, {"ABA","C","ABA"}, or {"ABACABA"}, among others.
You are given a string s. Return the minimum possible number of substrings in a palindrome partition of s.
Input
Input starts with an integer T (≤ 40), denoting the number of test cases.
Each case begins with a non-empty string s of uppercase letters with length no more than 1000.
Output
For each case of input you have to print the case number and the desired result.
Sample Input
3
AAAA
ABCDEFGH
QWERTYTREWQWERT
Sample Output
Case 1: 1
Case 2: 8
Case 3: 5
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;char a[1010];int dp[1010];int main(){int n,r,m,ca=1;scanf("%d",&r);while(r--){scanf("%s",a+1); n=strlen(a+1); for(int i=1;i<=n;i++)dp[i]=i; m=n; int i,j,k,s,t; for( i=1;i<n;i++){int x,sum;if(a[i]==a[i+1]){sum=0;x=i;for(j=i,k=i+1;j>=1,k<=n;j--,k++){if(a[j]!=a[k] )break;if(a[j]==a[i] && a[k]==a[i]) sum+=2;}s=j+1;t=k-1; dp[t]=min(dp[t],dp[s-1]+1); if(dp[t]==dp[s-1]+1){if(sum==t-s+1)for(int l=s+1;l<=t;l++)dp[l]=dp[s]; else for(int l=i+1;l<=t;l++){dp[l]=dp[x-1]+1;x--; }for(int l=t+1;l<=n;l++)dp[l]=dp[t]+l-t; } } if(a[i-1]==a[i+1] && i>=2){sum=1;x=i-1;for(j=i-1,k=i+1;j>=1,k<=n;j--,k++){if(a[j]!=a[k] )break;if(a[j]==a[i] && a[k]==a[i]) sum+=2;} s=j+1;t=k-1; dp[t]=min(dp[t],dp[s-1]+1);if(dp[t]==dp[s-1]+1){if(sum==t-s+1)for(int l=s+1;l<=t;l++)dp[l]=dp[s]; else for(int l=i+1;l<=t;l++){dp[l]=dp[x-1]+1; x--; }for(int l=t+1;l<=n;l++)dp[l]=dp[t]+l-t; } }} printf("Case %d: %d\n",ca++,dp[n]);}}
- D - Palindrome Partitioning
- Palindrome partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Java Socket长链接 异步读写 实例
- 重述:JavaScript学习总结(二)
- c++ primer习题9.34, 9.35, 9.40
- 内核线程、轻量级进程、用户线程
- jar、war、ear三种文件的区别
- D - Palindrome Partitioning
- [Leap Motion开发系列]win32应用的环境配置[2013-11-2更新]
- 查看自己trace出来的文件路径
- 黑马程序员——IO File类,Properties,打印流 ,合并流
- JAVA程序设计教程-第2版-雍俊海 介绍以及 PDF+源代码+ppt 下载链接
- ios开发技术——播放系统wav格式的音乐
- Android必懂知识--权限大全
- 双网卡双网关实例问题解决
- 天乙社区社区首页分析(一)