PAT (Advanced Level) Practice 1031 Hello World for U (20 分)

我不是女神ヾ 2022-05-07 01:00 282阅读 0赞

1031 Hello World for U (20 分)

Given any string of N (≥5) characters, you are asked to form the characters into the shape of U. For example, helloworld can be printed as:

  1. h d
  2. e l
  3. l r
  4. lowo

That is, the characters must be printed in the original order, starting top-down from the left vertical line with n1 characters, then left to right along the bottom line with n2 characters, and finally bottom-up along the vertical line with n3 characters. And more, we would like U to be as squared as possible — that is, it must be satisfied that n1=n3=max { k | k≤n2 for all 3≤n2≤N } with n1+n2+n3−2=N.

Input Specification:

Each input file contains one test case. Each case contains one string with no less than 5 and no more than 80 characters in a line. The string contains no white space.

Output Specification:

For each test case, print the input string in the shape of U as specified in the description.

Sample Input:

  1. helloworld!

Sample Output:

  1. h !
  2. e d
  3. l l
  4. lowor

AC代码:

  1. /*1031 Hello World for U
  2. 给你一字符串,将它以'U型'输出
  3. 其中n1=n3分别表示U型的左右两侧的字符数,n2等于底部的字符数, N表示字符串里字符的总数
  4. 其中满足关系n1=n3=max{k|k<=n2, 3<=n2<=N}, n1+n2+n3-2=N
  5. */
  6. #include <iostream>
  7. #include <string>
  8. using namespace std;
  9. int main(){
  10. string s;
  11. cin >> s;
  12. int N = s.length();
  13. int n1 = (N + 2) / 3;
  14. int n2 = N + 2 - 2*n1;
  15. //将U型横着输出
  16. for(int i = 0; i < n1-1; i++) {
  17. cout << s[i];
  18. //输出U中间空的字符串
  19. for(int j = 0; j < n2-2; j++){
  20. cout << " ";
  21. }
  22. cout << s[N-i-1] << endl;
  23. }
  24. //输出最底部的那一行字符串
  25. for(int k = 0; k < n2; k++) {
  26. cout << s[n1-1+k];
  27. }
  28. return 0;
  29. }

发表评论

表情:
评论列表 (有 0 条评论,282人围观)

还没有评论,来说两句吧...

相关阅读