1031. Hello World for U (20)

来源:互联网 发布:新媒体网络部面试问题 编辑:程序博客网 时间:2024/06/10 20:59

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  de  ll  rlowo
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   dl   l

lowor

解析:本体本质上是求最值,最值问题和方程问题最终求得的结果都是唯一的(本质上讲),但后者是通过解析的方法来获得结果,前者则需要通过迭代逼近的方法求得最值。所以解决最值问题首要的问题是确定值的选择范围,然后确定最值的寻找方法。确定范围很简单,就是把max从上面的描述表达式子中去掉,就可以看清楚挑选的范围,因为数据量不大,所以这里采用遍历所有来确定最值。

/*************************************************************************> File Name: 1031.c> Author: yuebo> Mail: yuebowhu@163.com> Created Time: Sat 13 May 2017 06:49:02 PM CST ************************************************************************/#include<stdio.h>#include <stdlib.h>#include <string.h>int compute(int N){    int n1, n2, result1 = 0;    for (n2 = N; n2 >= 3; n2--)        for (n1 = n2; n1 > 0; n1--)            if (n1 * 2 + n2 -2 == N && n1 > result1)                result1 = n1;    return result1;}int main(){    int len_str;    char str[128];    int n1, n2, n3;    int i, j;        scanf("%s", str);    len_str = strlen(str);    n1 = n3 = compute(len_str);    n2 = len_str + 2 - 2 * n1;    for (i = 0; i < n1-1; i++)    {        printf("%c", str[i]);        for (j = 0; j < n2-2; j++)            printf(" ");        printf("%c", str[len_str-1-i]);        printf("\n");    }    for (j = 0; j < n2; j++)        printf("%c", str[j+n1-1]);    printf("\n");    return 0;}


0 0