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 n​1​​ characters, then left to right along the bottom line with n​2​​ characters, and finally bottom-up along the vertical line with 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​​=max { k | k≤n​2​​ for all 3≤n​2​​≤N } with 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

题目大意

给定任何N(≥5)个字符的字符串,要求您将这些字符形成U的形状。例如,helloworld可以打印为:

h d
e l
l r
lowo
也就是说,字符必须按原来的顺序打印,从左垂直行开始自上而下打印n 1个字符,然后从左到右沿底线打印n 2个字符,最后从下到上沿垂直行打印n 3个字符。而且,我们希望U是尽可能平方的,也就是说,它必须满足n 1=n 3=max{k | k≤n 2,对于所有3≤n 2≤n},n 1+n 2+n 3−2=n。

输入规格:

每个输入文件包含一个测试用例。每个大小写包含一个行中不少于5个且不超过80个字符的字符串。字符串不包含空格。

输出规格:

对于每个测试用例,按描述中指定的U形打印输入字符串。

样本输入:

helloworld!

样本输出:

h !
e d
l l
lowor

思路分析

利用二维数组直接输出。

#include
#include
using namespace std;
int main()
{
     
	string s;
	cin >> s;
	int cnt = 0;
	int len = s.size();
	int n1 = (len+2)/3-1;
	int n2 = (len+2)/3+(len+2)%3;
	char a[30][30]={
     ' '};
    //fill(a[0],a[0]+30*30,' ');
	for (int i = 0; i < n1; i++)
	{
     
		a[i][0] = s[cnt++];

	}
	for (int i = 0; i < n2; i++)
	{
     
		a[n1][i] = s[cnt++];
	}
	for (int i = n1-1; i >= 0; i--)
	{
     
		a[i][n2-1] = s[cnt++];
	}
	for (int i = 0; i < n1+1; i++)
	{
     
		for (int j = 0; j < n2; j++)
		{
     
			cout << a[i][j];
		}
		cout << endl;
	}
	return 0;
}

总结

这个题没什么难度,倒腾了这么久是因为!
二维字符数组的初始化!o(╥﹏╥)o
对于二维字符数组千万不能像这样初始化:char a[30][30]={’ '},这样的初始化是指对第一个元素进行初始化 。其余的元素没有初始化,为0.

你可能感兴趣的:(PAT,A)