PTA 团队天梯赛║L1-039 古风排版
一、题目要求
中国的古人写文字,是从右向左竖向排版的。本题就请你编写程序,把一段文字按古风排版。
输入格式:
输入在第一行给出一个正整数N(<100),是每一列的字符数。第二行给出一个长度不超过 1000 的非空字符串,以回车结束。
输出格式:
按古风格式排版给定的字符串,每列N个字符(除了最后一列可能不足N个)。
输入样例:
输出样例:
二、解题思路
利用一个二维字符数组存放字符串比较容易操作与理解,输入行数后就可以根据字符串长度确定输出时的列数,然后从最后一列开始输入字符串的每一个字符,直至字符串结束。最后顺序输出二位字符数组即可。
三、代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include <bits/stdc++.h> using namespace std;
int main() { string s; char a[100][100]={' '}; int row, col, k = 0; cin >> row; getchar(); getline(cin,s); if(s.length()%row == 0) col = s.length() / row; else col = s.length() / row + 1; for(int i=col-1; i>=0; i--) { for(int j=0; j<row; j++) { a[j][i] = s[k++]; if(k==s.length()) break; } }
for(int i=0; i<row; i++) { for(int j=0; j<col; j++) { cout << a[i][j]; } cout << endl; } cout << endl;
return 0; }
|
四、反思总结
第一版中错误的使用 a[100] [100] = ‘ ‘ 进行初始化字符数组,导致不能通过测试。
改进后代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <bits/stdc++.h> using namespace std;
int main() { string s; char a[100][100]; for(int i = 0; i < 100; i++){ for(int j = 0; j < 100; j++){ a[i][j] = ' '; } } int row, col, k = 0; cin >> row; getchar(); getline(cin,s); if(s.length()%row == 0) col = s.length() / row; else col = s.length() / row + 1; for(int i=col-1; i>=0; i--) { for(int j=0; j<row; j++) { a[j][i] = s[k++]; if(k==s.length()) break; } }
for(int i=0; i<row; i++) { for(int j=0; j<col; j++) { cout << a[i][j]; } cout << endl; }
return 0; }
|