题目大意:还原(解码)字符串。该字符串str首先被平均分成n列,每列r行,其中n * r ≤ len(str) ,多余位置用'x'添补。字符串按列填充,然后将偶数列翻转,然后按行获得输入串。
解题思路:逆向思维。先将输入串按行填充 r * n的矩阵,然后偶数列翻转,最后按列输出输出串。
代码如下:
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 5 const int ROWS = 105; 6 const int COLS = 25; 7 8 char m[ROWS][COLS]; 9 char str[ROWS * 2]; 10 char ans[ROWS * 2]; 11 int n; 12 13 int main() { 14 while (cin >> n, n) { 15 cin >> str; 16 int len = strlen(str); 17 18 int r = (len + n - 1) / n; 19 20 for (int i = 0; i < r; i++) { 21 for (int j = 0; j < n; j++) { 22 m[i][j] = str[i*n + j]; 23 } 24 } 25 26 for (int i = 1; i < r; i += 2) { 27 for (int j = 0; j * 2 < n; j++) { 28 char temp = m[i][j]; 29 m[i][j] = m[i][n - j - 1]; 30 m[i][n - j - 1] = temp; 31 } 32 } 33 34 int k = 0; 35 for (int i = 0; i < n; i++) { 36 for (int j = 0; j < r; j++) { 37 ans[k++] = m[j][i]; 38 } 39 } 40 ans[k++] = '