Palindrome
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 52971 | Accepted: 18274 |
Description
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.
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.
回文数是一个对称的字符串,就是一个从左往右读和从右往左读相同的字符串。你来写个程序,给你个字符串,添加最少的字符使得这个字符串成为回文数。
举个栗子,插入两个字符,
"Ab3bd"就可以变成一个回文数("dAb3bAd" or "Adb3bdA")。插入如果少于两个字符,则没办法组成回文数。
Input
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.
输入第一行一个N,
3 <= N <= 5000。第二行一个长度为N的字符串,字符串有大写字母小写字母和数字,区分大小写
Output
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
输出一行,就一个数字,输出最少添加多少个字符能变成回文数
Sample Input
5 Ab3bd
Sample Output
2
Source
这道题就是把序列取反然后做一个LCS最长公共子序列,之后再用N减去得答案,
看起来还蛮简单的,结果dp空间开不出来。5000*5000必死无疑,后来发现dp[i]就跟dp[i-1]状态有关,那就可以用滚动数组。。滚动数组说的蛮好听的,其实就是两个状态,可以用一维空间加两个变量代替。。。不过我还是二维数组了。。。效率不算高,但好歹能过题。。。
#include <stdio.h>
#include <string.h>
int max_num(int a, int b);
void reverse(char *str);
int main(void){
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
char str_a[5555], str_b[5555];
int c[2][5555];
int i, j;
int length;
int flag;
scanf("%d", &length);
scanf("%s", str_a + 1);
for (i = 0;i < length + 1;i ++)
str_b[i] = str_a[length - i + 1];
//printf("%s %s\n", str_a + 1, str_b + 1);
for (j = 0;j < length + 1;j ++){
c[0][j] = c[1][j] = 0;
}
flag = 0;
for (i = 1;i < length + 1;i ++){
flag = 1 - flag;
for (j = 1;j < length + 1;j ++){
if (str_a[i] == str_b[j]){
c[flag][j] = c[1 - flag][j - 1] + 1;
//printf("fir = %d\n", c[flag][j]);
}else{
c[flag][j] = max_num(c[1-flag][j], c[flag][j - 1]);
//printf("sed = %d\n", c[flag][j]);
}
}
}
printf("%d\n", length - c[flag][length]);
return 0;
}
int max_num(int a, int b){
return a > b ? a : b;
}