前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【PAT甲级】Hello World for U

【PAT甲级】Hello World for U

作者头像
喜欢ctrl的cxk
发布2019-11-08 14:18:49
3440
发布2019-11-08 14:18:49
举报
文章被收录于专栏:Don的成长史

版权声明:本文为博主原创文章,遵循 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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
helloworld!

Sample Output:

代码语言:javascript
复制
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代码:

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/04/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem Description:
  • Input Specification:
  • Output Specification:
  • Sample Input:
  • Sample Output:
  • 解题思路:
  • AC代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档