|Time Limit: 3000MS||Memory Limit: 65536K|
|Total Submissions: 31809||Accepted: 10621|
A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
It's the most basic longest common subsequence problem.
PS: Take care of the size of the array, otherwise, it will exceed the memory limit.
Source Code://Mon Apr 12 10:33:15 CDT 2010
using namespace std;
int LongestCommonSubstring(string A, string B)
int N = A.size();
int M = B.size();
vector<vector<int> > v(2, vector<int>(M+1, 0));
for(int i=0; i<=N; i++)
for(int j=0; j<=M; j++)
if(i==0 || j==0)
v[i%2][j] = 0;
else if(A[i-1] == B[j-1])
v[i%2][j] = v[(i-1)%2][j-1] + 1;
v[i%2][j] = max(v[(i-1)%2][j], v[i%2][j-1]);
int main( int argc, const char* argv )
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
while(cin >> N)
cin >> str1;
string str2 = str1;
cout << N - LongestCommonSubstring(str1, str2) << endl;