zoukankan      html  css  js  c++  java
  • 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("
    ");
        }
        */
    
        //法二:直接枚举输出
        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
    ", str[N-1-i]);
        }
        for(int i=0; i<n2; i++)
            printf("%c", str[n1-1+i]);
    
        return 0;
    }
            
  • 相关阅读:
    Spark提交任务到集群
    在Spark中使用Kryo序列化
    Linux用户与用户组的详解
    Linux一键安装PHP/JAVA环境OneinStack
    Redis常用命令
    MySQL高效分页解决方案集
    linux 发邮件
    Linux 安全
    Linux Shell 文本处理工具集锦
    MySQL 获得当前日期时间(以及时间的转换)
  • 原文地址:https://www.cnblogs.com/claremore/p/6548210.html
Copyright © 2011-2022 走看看