PAT_A 1031 Hello World for U
PAT_A 1031 Hello World for U
分析
按照题目要求进行处理即可,即将原字符串(长度为N)按U型输出。n1=n3为高,n2为宽,且n1<=n2-1,3<=n2<=N;这里的n1比题中的n1小一,原因是题中的n1加上了与n2的交点。
题目的描述
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=ma**x { 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
AC的代码
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int n1=0,n2=0;
int N = s.length();
n2 = N/3;
if(n2<3)n2=3;
n1 = (N-n2)/2;
while(n1>n2-1){
n1-=1;
n2+=2;
}
n2+=N-(2*n1+n2);
for(int i=0;i<n1;i++){
string t(n2,' ');
t[0]=s[i];t[n2-1]=s[N-1-i];
cout<<t<<endl;
}
cout<<s.substr(n1,n2)<<endl;
return 0;
}
本文来自博客园,作者:ghosteq,转载请注明原文链接:https://www.cnblogs.com/ghosteq/p/15841243.html