简单的DP 统计回文序列数量(注意是序列不是串)
f[i][j]= f[i+1][j]+f[i][j-1]+1 s[i]==s[j]
f[i][j]= f[i+1][j]+f[i][j-1]-f[i+1][j-1] s[i]!=s[j]
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, Z, TOT andMADAM 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 |
Russian Olympic Camp
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
typedef long long ll;
char str[100];
ll f[100][100];
int main()
{
int cs;
scanf("%d",&cs);
while(cs--)
{
scanf("%s",str);
memset(f,0,sizeof(f));
int len=strlen(str);
for(int i=0;i<len;i++)
f[i][i]=1;
for(int i=2;i<=len;i++)
{
for(int j=0;j+i-1<len;j++)
{
if(str[j]==str[j+i-1])
f[j][j+i-1]=f[j+1][j+i-1]+f[j][j+i-2]+1;
else
f[j][j+i-1]=f[j+1][j+i-1]+f[j][j+i-2]-f[j+1][j+i-2];
}
}
printf("%lld\n",f[0][len-1]);
}
return 0;
}
本文介绍了一种使用动态规划(DP)算法来统计给定序列中可能的回文子序列数量的方法。针对每个测试案例,算法通过填充一个二维数组来确定在去除若干字符后能使序列成为回文的不同方式的数量。

366

被折叠的 条评论
为什么被折叠?



