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

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

题目描述:

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.

译:给你一个 N (≥5) 个字符的字符串,要求你将这些字符组成 U 的形状。例如, helloworld 可以被打印出来:

h  d
e  l
l  r
lowo

也就是说,字符必须按照原来的顺序答应,从左垂线开始从上往下有 n1 行字符,最后一行从左至右有 n2 个字符,最后从下往上垂线上有 n3 个字符。更多的是,我们希望 U 尽可能的正方,也就是说它必须满足要求 n1=n3=max { k | k≤n2 for all 3≤n2≤N } 并且 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.

译:每个输入文件包含一个测试用例,每个用例包含一行不少于 5 个字符不超过 80 个字符的字符串。这个字符串不包含空格。


Output Specification (输出说明):

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

译:对于每个测试用例,将输入的字符串按描述的 U 形状输出。


Sample Input (样例输入):

helloworld!

Sample Output (样例输出):

h   !
e   d
l   l
lowor

The Idea:

首先利用 string 存储字符串,根据 n1=n3=max { k | k≤n2 for all 3≤n2≤N } 并且 n1+n2+n3−2=N. 很容易可以推出:n1 = n3 = (N + 2) / 3 ; n2 = N + 2 - 2 * n1 ; 也就是得到了 U 形状的行与列。

然后按照要求打印即可。


The Codes:

#include<bits/stdc++.h>
using namespace std;
int main(){
	string s ;
	cin >> s ; 
	int n1 = (s.size() + 2) / 3 ; // 得到 U 形状有多少行
	int n2 = s.size() - 2 * n1 + 2 ; // 得到  U 形状有多少列
	for(int i = 0 ; i < n1 - 1 ;){ // 除最后一行以外
		printf("%c" , s[i ++]) ; // 输出每行最左边的字符
		for(int k = 1 ; k < n2 - 1 ; k ++) printf(" ") ; // 输出中间的空格
		printf("%c\n" , s[s.size() - i]) ; // 输出每行最右边的字符
	}
	cout<< s.substr(n1 - 1 , n2) << endl ; // 输出最后一行
	return 0;
}

上一篇:SysUtils.StrComp、SysUtils.StrIComp


下一篇:一维数组和二维数组中学习到的重要的点