PAT A1031 Hello World for U

PAT A1031 Hello World for U

题目描述:

  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:
  h   d
  e    l
  l     r
  lowo

  That is, the characters must be printed in the original order, starting top-down from the left vertical line with n​1​​ characters, then left to right along the bottom line with n​2​​ characters, and finally bottom-up along the vertical line with n​3​​ characters. And more, we would like U to be as squared as possible -- that is, it must be satisfied that n​1​​=n​3​​=max { k | k≤n​2​​ for all 3≤n​2​​≤N } with n​1​​+n​2​​+n​3​​−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:
  helloworld!
  

  Sample Output:
  h     !
  e    d
  l      l
  lowor

参考代码:

 1 /***********************************************
 2 PAT A1031 Hello World for U
 3 ***********************************************/
 4 #include <iostream>
 5 #include <string>
 6 #include <vector>
 7 
 8 using namespace std;
 9 
10 //将字符串str按照U形输出
11 void printU(const string str, const int size) {
12     int n1, n2, n3;
13 
14     n1 = n2 = (size + 2) / 3;   //U形两个竖直边的高度
15     n3 = size - 2 * n1 + 2;     //U形底边的长度
16 
17     //输出U形非底边的部分
18     for (int i = 0; i < n1 - 1; ++i) {
19         cout << str[i];
20         for (int j = 0; j < n3 - 2; ++j) {
21             cout << ' ';
22         }
23         cout << str[size - 1 - i] << endl;
24     }
25     
26     //输出U形的底边
27     for (int i = 0; i < n3; ++i) {
28         cout << str[n1 - 1 + i];
29     }
30 }
31 
32 int main() {
33     string str;
34 
35     cin >> str;
36 
37     printU(str, str.size());
38 
39     return 0;
40 }

注意事项:

  无。

posted @ 2019-08-21 01:32  多半是条废龙  阅读(97)  评论(0)    收藏  举报