Saturday, August 28, 2010


Problem Links:




Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 31809Accepted: 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.

Sample Input

Sample Output

IOI 2000


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
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

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]);
    return v[N%2][M];

int main( int argc, const char* argv[] )
    freopen("", "r", stdin);
    freopen("output.out", "w", stdout);
    int N;
    while(cin >> N)
        string str1;
        cin >> str1;
        string str2 = str1;
        reverse(str2.begin(), str2.end());
        cout << N - LongestCommonSubstring(str1, str2) << endl;
    return 0;

No comments :