标签:algorithm inline 回文 letters public distinct ems cep amp
Input
Output
Sample Input
5 Ab3bd
Sample Output
2
f[j][i]表示从i这里开始,一直往后j个字符的这一段改成回文串最少需要添加的字符。然后第一维可以拉去滚动。转移是显然的。。
1 /** 2 * poj 3 * Problem#1159 4 * Accepted 5 * Time:782ms 6 * Memory:748k 7 */ 8 #include<iostream> 9 #include<sstream> 10 #include<cstdio> 11 #include<cmath> 12 #include<cstdlib> 13 #include<cstring> 14 #include<cctype> 15 #include<queue> 16 #include<set> 17 #include<map> 18 #include<stack> 19 #include<vector> 20 #include<algorithm> 21 #ifdef WIN32 22 #define AUTO "%I64d" 23 #else 24 #define AUTO "%lld" 25 #endif 26 using namespace std; 27 typedef bool boolean; 28 #define smin(a, b) (a) = min((a), (b)) 29 #define smax(a, b) (a) = max((a), (b)) 30 template<typename T> 31 inline void readInteger(T& u){ 32 char x; 33 int aFlag = 1; 34 while(!isdigit((x = getchar())) && x != ‘-‘); 35 if(x == ‘-‘){ 36 aFlag = -1; 37 x = getchar(); 38 } 39 for(u = x - ‘0‘; isdigit((x = getchar())); u = u * 10 + x - ‘0‘); 40 ungetc(x, stdin); 41 u *= aFlag; 42 } 43 44 template<typename T>class Matrix{ 45 public: 46 T *p; 47 int lines; 48 int rows; 49 Matrix():p(NULL){ } 50 Matrix(int rows, int lines):lines(lines), rows(rows){ 51 p = new T[(lines * rows)]; 52 } 53 T* operator [](int pos){ 54 return (p + pos * lines); 55 } 56 }; 57 #define matset(m, i, s) memset((m).p, (i), (s) * (m).lines * (m).rows) 58 59 int n; 60 char* str; 61 62 inline void init() { 63 readInteger(n); 64 str = new char[(const int)(n + 3)]; 65 getchar(); 66 gets(str + 1); 67 } 68 #define idx(i) ((i < 0) ? (i + 3) : (i)) 69 70 //Matrix<int> f; 71 int f[3][5005]; 72 inline void solve() { 73 // f = Matrix<int>(3, n + 1); 74 for(int i = 1; i <= n; i++) 75 f[0][i] = 0; 76 for(int i = 1; i < n; i++) 77 f[1][i] = (str[i] == str[i + 1]) ? (0) : (1); 78 int t = 2; 79 for(int k = 2; k < n; k++) { 80 for(int i = 1; i + k <= n; i++) { 81 int j = i + k; 82 if(str[i] == str[j]) f[t][i] = f[idx(t - 2)][i + 1]; 83 else f[t][i] = min(f[idx(t - 1)][i], f[idx(t - 1)][i + 1]) + 1; 84 } 85 t = (t == 2) ? (0) : (t + 1); 86 } 87 printf("%d", f[idx(t - 1)][1]); 88 } 89 90 int main() { 91 init(); 92 solve(); 93 return 0; 94 }
标签:algorithm inline 回文 letters public distinct ems cep amp
原文地址:http://www.cnblogs.com/yyf0309/p/7126274.html