题意:给一个字符串,让你添加字符使其变成回文字符串,问最少添加几个
思路:开始真没思路,后来看别人的提示,可以把这个问题转化成上一题的思路——最长公共子序列问题。
就是把这个串反转,然后求这两个串的最长公共子序列,用原串长度减去最长公共子序列长度不就是要添加的字符个数啦!
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
string s,t;
int dp[1005][1005],len,T;
int Max(int a,int b){return a>b?a:b;}
void input()
{
cin >> s;
t = s;
reverse(t.begin(),t.end());
len = s.size();
memset(dp,0,sizeof(dp));
}
void solve()
{
for(int i = 0 ; i < len ; i++)
for(int j = 0 ; j < len ; j++)
{
if(t[i] == s[j])
dp[i+1][j+1] = dp[i][j]+1;
else{
dp[i+1][j+1] = Max(dp[i+1][j],dp[i][j+1]);
}
}
cout << len - dp[len][len] << endl;
}
int main()
{
#ifdef H_R
freopen("in.txt","r",stdin);
#endif // H_R
cin.tie(false);
ios::sync_with_stdio(false);
while( cin >> T )
{
while(T--)
{
input();
solve();
}
}
return 0;
}