1. POJ 1159 Palindrome
题目链接:
http://poj.org/problem?id=1159
递推式为
if a[i]==a[j] dp[i][j]=d[i+1][j-1];
else dp[i][j]=min(dp[i+1][j],dp[i][j-1]);
代码如下:
//include <bits/stdc++.h>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <time.h>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll MOD = 1000000007;
const int maxn = 5*1e3+5;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
template <class T>
inline bool scan_d(T &ret) {
char c; int sgn;
if (c = getchar(), c == EOF) return 0;
while (c != '-' && (c<'0' || c>'9')) c = getchar();
sgn = (c == '-') ? -1 : 1;
ret = (c == '-') ? 0 : (c - '0');
while (c = getchar(), c >= '0'&&c <= '9') ret = ret * 10 + (c - '0');
ret *= sgn;
return 1;
}
int n;
short dp[maxn][maxn];
char a[maxn];
int main()
{
while(scanf("%d",&n)!=EOF)
{
scanf("%s",a+1);
for (int i=1;i<=n;i++)
{
dp[i][i]=0;
}
for (int i=1;i<n;i++)
{
if(a[i]!=a[i+1]) dp[i][i+1]=1;
else dp[i][i+1]=0;
}
for (int i=2;i<=n;i++)
{
for (int j=1;i+j<=n;j++)
{
if(a[j]==a[i+j])
{
dp[j][i+j]=dp[j+1][i+j-1];
}
else
{
dp[j][i+j]=min(dp[j+1][i+j],dp[j][i+j-1])+1;
}
}
}
printf("%d\n",dp[1][n]);
}
return 0;
}
2. HDU 4632 Palindrome subsequence
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=4632
参考题解:
https://blog.csdn.net/l954688947/article/details/50620302
代码如下:
//include <bits/stdc++.h>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <time.h>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll MOD = 10007;
const int maxn = 1e3+5;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
template <class T>
inline bool scan_d(T &ret) {
char c; int sgn;
if (c = getchar(), c == EOF) return 0;
while (c != '-' && (c<'0' || c>'9')) c = getchar();
sgn = (c == '-') ? -1 : 1;
ret = (c == '-') ? 0 : (c - '0');
while (c = getchar(), c >= '0'&&c <= '9') ret = ret * 10 + (c - '0');
ret *= sgn;
return 1;
}
int t;
int n;
char a[maxn];
ll dp[maxn][maxn];
int main()
{
scanf("%d",&t);
int Case=0;
while(t--)
{
Case++;
scanf("%s",a+1);
int len=strlen(a+1);
memset (dp,0,sizeof(dp));
for (int i=1;i<=len;i++)
{
dp[i][i]=1;
}
for (int i=1;i<=len;i++)
{
for (int j=i-1;j>=1;j--)
{
dp[j][i]=(dp[j][i]+dp[j+1][i]+dp[j][i-1]-dp[j+1][i-1]+MOD)%MOD;
if(a[i]==a[j])
{
dp[j][i]=(dp[j][i]+dp[j+1][i-1]+1+MOD)%MOD;
}
}
}
printf("Case %d: %lld\n",Case,dp[1][len]);
}
return 0;
}
本文探讨了两道经典算法题目:POJ1159回文串和HDU4632最长回文子序列。通过动态规划解决回文串的最小编辑距离和寻找字符串中最长的回文子序列。提供了详细的算法思路与代码实现。

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



