题目:http://poj.org/problem?id=1159
AC代码(C++):
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#include <string.h>
#include <bitset>
#define INF 0xfffffff
#define MAXN 100105
using namespace std;
int n;
char str1[5005];
char str2[5005];
short int dp[5005][5005];
void strcpyrev(char* d, char* s){
int len = strlen(s);
for(int i = 0; i < len; i++){
d[i] = s[len-i-1];
}
d[len] = '\0';
}
int main(){
cin>>n>>str1;
strcpyrev(str2,str1);
memset(dp,0,sizeof(dp));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(str1[i-1] == str2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
}
else if(dp[i-1][j] >= dp[i][j-1]){
dp[i][j] = dp[i-1][j];
}
else{
dp[i][j] = dp[i][j-1];
}
}
}
cout<<n-dp[n][n];
}
总结: 最长公共子序列. 答案=输入字符串长度-输入字符串与其逆字符串的最长公共子序列长度. 我也是由poj1080题启发才想到这样做的, 但还是交了3次才AC. 第一次是因为strrev不在oj库内编译错误, 第二次是5000*5000的dp数组太大超内存, 改成short int就好了.