PAT(A) 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 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
#include <fstream>
using namespace std;
#include <cstdio>
#include <cstring>

int main()
{
    int N, n1, n2, n3;
    char str[100], ans[40][40]; //ans[][]用于法一:二维数组方式输出

    //输入(下面的方法皆可)
    //FILE *fp;
    //fp=fopen("test.txt", "r");
    //fscanf(fp, "%s", &str);
    scanf("%s", &str);

    //ifstream fin("test.txt");
    //fin >> str;
    //gets(str);

    //划重点:列出前几项then找规律推出n1,n2,n3,N的关系
    N=strlen(str);  //获取长度
    n1=n3=(N+2)/3;
    n2=N+2-n1-n3;

    /*输出
    //法一:二维数组ans[][]方式输出
    for(int i=1; i<=n1; i++){
        for(int j=1; j<=n2; j++)
            ans[i][j]=' ';         //初始化二维数组;全部赋为空格
    }
    int pos=0;                    //pos用来记录str[]的下标
    for(int i=1; i<=n1; i++)
        ans[i][1]=str[pos++];     //str[]从下标0开始存数据
    for(int j=2; j<=n2; j++)
        ans[n1][j]=str[pos++];
    for(int i=n3-1; i>=1; i--)
        ans[i][n2]=str[pos++];

    for(int i=1; i<=n1; i++){     //输出整个二维数组
        for(int j=1; j<=n2; j++)
            printf("%c", ans[i][j]);
        printf("\n");
    }
    */

    //法二:直接枚举输出
    for(int i=0; i<n1-1; i++){      //前n1-1行
        printf("%c", str[i]);
        for(int j=0; j<n2-2; j++)   //每行输出n2-2个空格
            printf(" ");
        printf("%c\n", str[N-1-i]);
    }
    for(int i=0; i<n2; i++)
        printf("%c", str[n1-1+i]);

    return 0;
}
        

 

posted @ 2017-03-14 14:12  claremz  阅读(213)  评论(0编辑  收藏  举报