【PAT甲级】Hello World for U

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/weixin_42449444/article/details/89435176

Problem Description:

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 n​1​​ characters, then left to right along the bottom line with n​2​​ characters, and finally bottom-up along the vertical line with n​3​​ characters. And more, we would like U to be as squared as possible -- that is, it must be satisfied that n​1​​=n​3​​=max { k | k≤n​2​​ for all 3≤n​2​​≤N } with n​1​​+n​2​​+n​3​​−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

解题思路:

膜柳神~ 真的大佬(博文链接:https://www.liuchuo.net/archives/2053),她的思路是:假设n = 字符串长度 + 2,因为2 * n1 + n2 = n,且要保证n2 >= n1, n1尽可能地大,分类讨论:① 如果n % 3 == 0,n正好被3整除,直接n1 == n2 == n3; ② 如果n % 3 == 1,因为n2要比n1大,所以把多出来的那1个给n2;③ 如果n % 3 == 2, 就把多出来的那2个给n2;所以得到公式:n1 = n / 3,n2 = n / 3 + n % 3。初始化char型数组为空格,然后将字符串按照u型填充进去,最后输出这个数组u即可。

AC代码:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str;
    getline(cin,str);  
    int n = str.length() + 2;
    int n1 = n/3;    //n1是左右两条竖线从上到下的字符个数
    int n2 = n1 + n%3;  //n2是底部横线从左到右的字符个数 
    char arr[30][30];
    memset(arr,' ',sizeof(arr));
    int cnt = 0;  //用来记录当前字符的下标
    for(int i = 0; i < n1; i++)  //先排列左边那条竖线的n1个字符 hell
    {
        arr[i][0] = str[cnt++];
    }
    for(int i = 1; i < n2-1; i++)  //再排列底部那条横线(除去最左最右字符外)的那n2-2个字符  owo
    {
        arr[n1-1][i] = str[cnt++];
    }
    for(int i = n1-1; i >= 0; i--)  //最后排列右边那条竖线的n1个字符  rld!
    {
        arr[i][n2-1] = str[cnt++];
    }
    //打印U型图案
    for(int i = 0; i < n1; i++)
    {
        for (int j = 0; j < n2; j++)
        {
            cout << arr[i][j];
        }
        cout << endl;
    }
    return 0;
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券