时间限制:
3000 ms | 内存限制:65535 KB
难度:
4
-
描述
- 所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的,比如"aba"。当然,我们给你的问题不会再简单到判断一个字符串是不是回文字符串。现在要求你,给你一个字符串,可在任意位置添加字符,最少再添加几个字符,可以使这个字符串成为回文字符串。
-
输入
-
第一行给出整数N(0<N<100)
接下来的N行,每行一个字符串,每个字符串长度不超过1000.
输出
- 每行输出所需添加的最少字符数 样例输入
-
1 Ab3bd
样例输出
-
2
来源
- IOI 2000 上传者
- hzyqazasdf
1 #include <iostream> 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <string> 5 #include <string.h> 6 #include <algorithm>//reverse 7 #include <vector> 8 using namespace std; 9 #define debug(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl 10 int dpth[1010][1011]; 11 12 int dphwzfc(char *bufings, int n); 13 int main(){ 14 int N; 15 scanf("%d", &N); 16 getchar(); 17 while (N--) { 18 char buf[1001] = {0}; 19 char s[1001] = {0}; 20 int result = 0; 21 scanf("%s", buf); 22 getchar(); 23 memset(dpth, 0x00, sizeof(dpth)); 24 int buflen = strlen(buf); 25 if(buflen == 0 || buflen == 1){ 26 printf("%d\n", result); 27 continue; 28 } 29 //int lcslen = 0; 30 int idx = buflen-1; 31 int sidx = 0; 32 while (idx >= 0) { 33 s[sidx++] = buf[idx--]; 34 } 35 //cout << sidx << endl; 36 s[sidx] = '\0'; 37 // for (int i = 0; i < buflen; ++i) { 38 // if(s[0] == buf[i]){ 39 // dpth[0][i] = 1; 40 // }else { 41 // dpth[0][i] = 0; 42 // } 43 // if(s[i] == buf[0]){ 44 // dpth[i][0] = 1; 45 // }else { 46 // dpth[i][0] = 0; 47 // } 48 // } 49 50 for (int i = 0; i < buflen; ++i) { 51 for (int j = 0; j < buflen; ++j) { 52 if(s[i] == buf[j]){ 53 dpth[i+1][j+1] = dpth[i][j]+1; 54 }else{ 55 dpth[i+1][j+1] = max(dpth[i+1][j], dpth[i][j+1]); 56 } 57 58 59 // if(dpth[i][j] > lcslen){ 60 // lcslen = dpth[i][j]; 61 // } 62 63 } 64 } 65 //cout << dpth[buflen-1][buflen-1] << endl; 66 result = buflen - dpth[buflen][buflen]; 67 printf("%d\n", result); 68 } 69 return 0; 70 }
滚动数组
滚动数组的作用在于优化空间,主要应用在递推或动态规划中(如01背包问题)。
滚动数组实际是一种节省空间的办法,时间上没啥优势,多用于DP中