Again Palindromes - UVa 10617 dp

探讨了如何通过删除字符使普通字符串变为回文串的方法总数,并提供了详细的DP算法实现思路及代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem I

Again Palindromes

Input: Standard Input

Output: Standard Output

Time Limit: 2 Seconds

 

A palindorme is a sequence of one or more characters that reads the same from the left as it does from the right. For example, ZTOTand MADAM are palindromes, but ADAM is not.

 

Given a sequence S of N capital latin letters. How many ways can one score out a few symbols (maybe 0) that the rest of sequence become a palidrome. Varints that are only  different by an order of scoring out should be considered the same.

 

Input

The input file contains several test cases (less than 15). The first line contains an integer T that indicates how many test cases are to follow.

 

Each of the T lines contains a sequence S (1≤N≤60). So actually each of these lines is a test case.

 

Output

For each test case output in a single line an integer – the number of ways.

 

Sample Input                             Output for Sample Input

3

BAOBAB

AAAA

ABA

22

15

5



题意:删除字符串中任意数量的字符,使得其成为一个回文串,问这种删法一共有多少种,不删也算一种。

思路:还是从边上往中间递推if(s[l]==s[r])  dp[l][r]=dp[l+1][r]+dp[l][r-1]+1;  else   dp[l][r]=dp[l+1][r]+dp[l][r-1]-dp[l+1][r-1];

AC代码如下:

#include<cstdio>
#include<cstring>
using namespace std;
long long dp[100][100],;
char s[110];
void dfs(int l,int r)
{ if(dp[l][r]>=0)
   return;
  if(l>r)
  { dp[l][r]=0;
    return;
  }
  dfs(l+1,r);
  dfs(l,r-1);
  dfs(l+1,r-1);
  if(s[l]==s[r])
   dp[l][r]=dp[l+1][r]+dp[l][r-1]+1;
  else
   dp[l][r]=dp[l+1][r]+dp[l][r-1]-dp[l+1][r-1];
}
int main()
{ int t,n,m,i,j,k,len;
  scanf("%d",&t);
  while(t--)
  { scanf("%s",s+1);
    len=strlen(s+1);
    memset(dp,-1,sizeof(dp));
    for(i=1;i<=len;i++)
     dp[i][i]=1;
    dfs(1,len);
    printf("%lld\n",dp[1][len]);
  }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值