PTA甲级——1031

1031 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:

1
2
3
4
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 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=ma x { k | kn2 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
2
3
4
h   !
e d
l l
lowor

思路

​ 实际上就是让我们构成的U尽可能让每一条边都相同,但是我们同时还需要满足n1+n2+n3−2=N这个公式,所以我们可以先计算一下n2=N+2/3, 然后N-n2判断一下这个数 % 2 是否等于0,如果不等于0则n2=n2+1即可。

代码

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
#include <iostream>
#include <cmath>

using namespace std;
int main(){
string s;
cin >> s;
int len = s.length();
int n1, n2;
n2 = ceil((len + 2) / 3.0);
n1 = len - n2;
if (n1 % 2 != 0) {
n2++;
}
n1 /= 2;
if (n2 == 2) {
cout << s[0] << " " << s[len - 1] << '\n';
cout << s[1] << s[2] << s[3] << s[4];
return 0;
}

for (int i = 0; i < n1; i++) {
cout << s[i];
for (int j = 2; j < n2; j++) cout << " ";
cout << s[len - i - 1] << '\n';
}

for (int i = n1; i <= n1 + n2 - 1; i++) cout << s[i];
return 0;
}