1031 Hello World for U (20 分)打印图形

版权声明:emmm……我也想成为大佬 https://blog.csdn.net/CV_Jason/article/details/84861352

题目

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 n 1 n_1 ​​ characters, then left to right along the bottom line with n 2 n_2 ​​ characters, and finally bottom-up along the vertical line with n 3 n​_3 characters. And more, we would like U to be as squared as possible – that is, it must be satisfied that n 1 = n 3 = m a x { k k n 2 , n 2 { 3 n 2 N } } n_​1=n_3​​ =max \{ k | k≤n_2 ,\forall n_2\in\{ 3≤n_2​​ ≤N\} \} with n 1 + n 2 + n 3 2 = N . n​_1+n_2+n_3 −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的形状。
  解题思路: 这个题的关键在于根据公式找到足够大的 n 1 n_1 使得整个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;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/CV_Jason/article/details/84861352