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 characters, then left to right along the bottom line with characters, and finally bottom-up along the vertical line with characters. And more, we would like U to be as squared as possible – that is, it must be satisfied that with
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的形狀。
解題思路: 這個題的關鍵在於根據公式找到足夠大的
使得整個U看起來足夠的squared,需要按照題目中的約束條件進行計算,由於資料量不是很大,所以直接暴力for迴圈即可。
/*
** @Brief:No.1031 of PAT advanced level.
** @Author:Jason.Lee
** @Date:2018-12-06
** @status: Accepted!
*/
#include<iostream>
using namespace std;
char input[81];
int n1,n2,n3,N;
void printU(){
if(n1==1){
printf("%s\n",input);
return;
}
for(int i=0;i<n1-1;i++){
printf("%c",input[i]);
for(int j=0;j<n2-2;j++){
printf(" ");
}
printf("%c\n",input[N-i-1]);
}
for(int i=n1-1;i<n1+n2-1;i++){
printf("%c",input[i]);
}
printf("\n");
}
int main(){
while(scanf("%s",input)!=EOF){
N = strlen(input);
if(N<=3){
n1=n3=1;
n2=N;
}else{
int max_n1 = -1;
for(n2=N;n2>=3;n2--){
for(n1=n2;n1>0;n1--){
if(n1*2+n2-2==N&&n1>max_n1){
max_n1 = n1;
}
}
}
n3 = n1 = max_n1;
n2 = N+2-n1-n3;
}
printU();
}
return 0;
}