题目描述如下:
1031 Hello World for U (20 point(s))
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=max { 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
遇到的问题以及解决思路:
题目的意思,n1和n3是两边的竖列,包括了最底下的字符,所以题目里会出现2,但是根据题目意思变通理解一下就好,保证最低行n2大于等于3,然后左右两列进行均等分配,如果出现两列的数量要大于底行n2了,那么再各自减去一个就好。
注意点!!!
c11标准里不再有gets(),然后可以使用fgets,但是要注意换行符也会被读入。
#include <cstdio>
#include <cstring>
//使用strlen
int main()
{
int lenth;
char strs[100];
//gets(strs);
//不要再用gets
fgets(strs, sizeof(strs), stdin);
//fgets会把换行符也读进去
//puts(strs);
lenth = strlen(strs) - 1;
int tempcol = (lenth - 3) / 2;
int temprow = lenth - 2 * tempcol;
while (tempcol >= temprow) {
tempcol--;
temprow += 2;
}
int n = 0;
for (int i = 1; i <= tempcol; i++) {
printf("%c", strs[n]);
for (int a = 1; a <= temprow - 2; a++) {
printf(" ");
}
printf("%c\n", strs[lenth - i]);
n++;
}
for(int j = 1; j <= temprow; j++) {
printf("%c", strs[n++]);
}
printf("\n");
return 0;
}