您的位置:首页 > 大数据 > 人工智能

uva 10617 Again Palindrome

2011-11-29 22:38 246 查看
题意:给你n个串(最长不超过60),问有多少种删去字符的方法使剩下的字符成为一个回文子串。

设map[x][y]为从x到y有多少个回文串。

当str[x]==str[y]的时候,我们要考虑x+1,y组成的回文串,x,y-1之间的回文串,但是两者都会计算x+1,y-1的回文串数,所以要减去,另外,因为str[x]==str[y],所以x+1,y-1之间的回文串也能和str[x],str[y]组成回文串,所以还要加上x+1,y-1之间的回文串。另外,str[x]与str[y]自身也组成了回文串。所以map[x][y]=map[x+1][y]+map[x][y-1]+1;

如果str[x]!=str[y],那么map[x][y]=map[x+1][y]+map[x][y-1];

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define LL long long
const int N=70;
LL map

;
bool vis

;
LL dp(int,int);
char str
;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(map,0,sizeof(map));
memset(vis,0,sizeof(vis));
scanf("%s",str+1);
int len=strlen(str+1);
printf("%lld\n",dp(1,len));
}
return 0;
}
LL dp(int x,int y)
{
bool &flag=vis[x][y];
LL &res=map[x][y];
if(flag) return res;
else if(x>=y)
{
flag=1;
if(x==y)res=1;
else res=0;return res;
}
else
{
if(str[x]==str[y]) res=max(res,dp(x+1,y)+dp(x,y-1)+1);
else res=max(res,dp(x+1,y)+dp(x,y-1)-dp(x+1,y-1));
flag=1;return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: