【PAT甲級】Hello World for U

  • 2019 年 11 月 8 日
  • 筆記

版權聲明:本文為博主原創文章,遵循 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;  }