[PAT A1031]Hello World for U
题目描述
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:
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=max { k | k≤n2 for all 3≤n2≤N } with n1+n2+n3−2=N.
输入格式
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.
输出格式
For each test case, print the input string in the shape of U as specified in the description.
输入样例
helloworld!
输出样例
h !
e d
l l
lowor
解析
- 题目大意就是输入一个字符串,让我们把它排成U型,并且假设U的左边竖行的长度为n1,右边竖行的长度为n3,最下面一行的长度是n2,要求是n1=n3,并且他们都要小于等于n2,在满足前面的两个条件下,要使得n1和n3足够大。
- 这样我们就可以找规律:
| n\N | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| n1 | 2 | 2 | 3 | 3 | 3 | 4 | 4 | 4 | 5 | 5 | 5 | 6 |
| n2 | 3 | 4 | 3 | 4 | 5 | 4 | 5 | 6 | 5 | 6 | 7 | 6 |
| n3 | 2 | 2 | 3 | 3 | 3 | 4 | 4 | 4 | 5 | 5 | 5 | 6 |
- 我们从中可以找到规律,就是对N除以3,向上取整,这样我们就可以得到n1和n3了,至于n2,直接拿N减就是了
#include<cmath>
#include<string>
using namespace std;
int main()
{
int N, n1, n2, n3;
string s;
cin >> s;
N = s.length();
n1 = ceil(N / 3.0);
n3 = n1;
n2 = N - n1 - n3;
int left = 0, right = N - 1; //使用left和right进行输出操作
for (int i = 0; i < n1 - 1; i++)
{
cout << s[left++];
for (int j = 0; j < n2; j++) cout << " ";
cout << s[right--];
cout << endl;
}
string s_kid = s.substr(left, right - left + 1); //取子字符串函数
cout << s_kid;
return 0;
}


被折叠的 条评论
为什么被折叠?



