PAT 1031 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 n1characters, 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:
helloworld!
Sample Output:
h !
e d
l l
lowor
题目大意:给出一个字符串,要求按U型输出n1,n3分别是左边和右边从第一个到最后一个的高度,n2是底层的长度,要求满足n1=n3(k|k<=n2),也就是列的高度要小于等于底部的长度。
//猛一看这个题目还挺难的,我的AC:
#include <iostream> #include <vector> #include<cstdio> using namespace std; int main() { string s; cin>>s; int size=s.size(); int n13,n2; n13=size/3; n2=n13+size%3; if(n13==n2){//如果两者相等的话,那么需要进行修改。 n13-=1; n2=size-n13*2; } for(int i=0;i<size;i++){ if(i<n13){ cout<<s[i]; for(int j=0;j<n2-2;j++){ cout<<' '; } cout<<s[size-1-i]<<'\n'; }else{ break; } } //打印n2层 for(int i=n13;i<size-n13;i++){ cout<<s[i]; } return 0; }
1.第一次提交时没通过,因为是如果是n13和n2相等的话,中间的空格就没办法输出了,所以就又添加了一个if判断是否相等,如果相等的话,那么就进行修改,便通过了。