算法笔记1993ProblemB Hello World For U

题目真洋气啊。。

题目描述

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.

输入

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.

输出

For each test case, print the input string in the shape of U as specified in the description.

样例输入

helloworld!

样例输出

在这里插入图片描述

思路

  1. 计算字符串长度len;
  2. 计算两边的字符数side=(len+2)/3;
  3. 计算最后一行中间的字符数(前面每行中间的空格数);
  4. 输出每行相应的字符。

思路有了,看看具体的要求。字符串的长度是N,n1,n3代表两边每列字符的数目。n2代表最后一行的字符数。题目中给了一个算式:

n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N } with n1 + n2 + n3 - 2 = N.

仔细研究这个算式,这里的k是不大于n2的,也就是说n1和n3是不大于n2且满足n1+n2+n3=N+2的最大值。那么自然有n1=n3=(N+2)/3,n2=N+2-(n1+n3)。也就是说设side为两边的字符数(包括最后一行的两端),则side=n1=n3=(N+2)/3。设mid为最后一行除去两端的两个字符后剩下的字符数,mid=N-side*2(总长度减去两边的字符数)。同时mid也是我们输出除最后一行外前面所有行需要空出的空格数。

最后如何在第一行输出第一个字符和最后一个字符呢?那自然是str[0]和str[len-1-i](len为字符串的长度,也就是N)。

代码展示

#include<cstdio>
#include<cstring>
int main() {
    char str[100];
    scanf("%s", str);
    int side, n2; // n1,n3代表两边每列字符的数目。n2代表最后一行的字符数
    int len = strlen(str);
    side = (len + 2) / 3;
    n2 = len + 2 - 2 * side;
    int mid; // mid为最后一行除去两端的两个字符后剩下的字符数
    mid = len - 2 * side;
    for(int i = 0; i < side - 1; i++) {
        printf("%c", str[i]);
        for(int j = 0; j < mid; j++) {
            printf(" ");
        }
        printf("%c\n", str[len - 1 - i]);
    }
    for(int j = 0; j < mid + 2; j++) {
            printf("%c", str[side + j - 1]);
        }
}

猜你喜欢

转载自blog.csdn.net/luminouswithyou/article/details/88625363