A1031 Hello World for U (20 point(s))

字符串按格式输出

1. 原文

原题

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:

1
2
3
4
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 $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:

1
helloworld!

Sample output:

1
2
3
4
h   !
e d
l l
lowor

2. 解析

结构存入数组中 再输出

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<cstdio>
#include<cstring>
const int maxn = 100;
char str[maxn];
char matrix[maxn][maxn];
int main(){
for (int i = 0; i < maxn; ++i)
{
for (int j = 0; j < maxn; ++j)
{
matrix[i][j]=' ';
}
}
scanf("%s",str);
int len = strlen(str)+2;
int n1 = len/3;
int n2 = len/3+len%3;
int idx = 0;
for (int i = 0; i < n1-1; ++i)
{
matrix[i][0]=str[idx++];
}
for (int i = 0; i < n2; ++i)
{
matrix[n1-1][i]=str[idx++];
}
for (int i = n1-2; i >= 0; i--)
{
matrix[i][n2-1]=str[idx++];
}
for (int i = 0; i < n1; ++i)
{
for (int j = 0; j < n2; ++j)
{
printf("%c",matrix[i][j]);
}
printf("\n");
}

return 0;
}

Way2:

直接根据图形输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<cstdio>
#include<cstring>
char str[100];
int main(){
freopen("A1031.txt","r",stdin);
scanf("%s",str);
int len = strlen(str)+2;
int n1 = len/3;
int n2 = len/3+len%3;
len-=2;
int idx = 0;
for (int i = 0; i < n1-1; ++i)
{
printf("%c",str[idx]);
for (int i = 1; i < n2-1; ++i)
{
printf(" ");
}
printf("%c\n",str[len-1-idx]);
idx++;
}
for (int i = 0; i < n2; ++i)
{
printf("%c",str[idx++]);
}
printf("\n");

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1031/
  • 发布时间: 2019-09-03 12:35
  • 更新时间: 2021-10-29 14:00
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!