1. 程式人生 > >PAT (Advanced Level) Practice 1031 Hello World for U (20)(20 分)

PAT (Advanced Level) Practice 1031 Hello World for U (20)(20 分)

1031 Hello World for U (20)(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 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

題解1:

題目要求每行字元的個數要大於等於每列字元的個數。

行列之間的字元計數是有重合的,左下角和右下角的字元計算了2次。為了計算和輸出方便,這裡考慮左右下角的兩個字元只算在行字元中,不算列字元。

以上述規則為前提,如果直接把總字元個數除以3得到列字元數,剩下作為行字元數,那麼在總字元數能被3整除的時候,行字元數比真正的列字元數小1。比如n=9, collum=9/3=3, row=9/3+9%3=3, 這時候實際上1列有4個字元,1行只有3個字元。

因此這裡把總字元數-1帶入計算,比如n=9, collum=(9-1)/3=2, row=(9-1)/3+(9-1)%3+1;(不能用row=(9-1)/3+9%3替代)。

最後先輸出前collum行列字元,再輸出最後一行row個行字元。

原始碼1:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string s;
  int count=0,l,b;
  cin>>s;
  count=s.size()-1;
  l=count/3;
  b=l+count%3+1;
  for(int i=0;i<l;i++)
  {
  cout<<s[i];
  for(int j=1;j<b-1;j++)
  cout<<" ";
  cout<<s[count-i]<<endl;
  }
  for(int i=l;i<=count-l;i++)
  cout<<s[i];
  return 0;
}

題解2:

重點在於計算行列的值。因為左右下角的字元被重複計算2次,所以也可以先總字元數+2,再運算。這時候計算的行列值,就是真正的行列值。比如n=9, collum=(9+2)/3=3,row=(9+2)/3+(9+2)%3=5.

原始碼2:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string s;
  int count=0,l,b;
  cin>>s;
  count=s.size()+2;
  l=count/3;
  b=l+count%3;
  for(int i=0;i<l-1;i++)
  {
  cout<<s[i];
  for(int j=1;j<b-1;j++)
  cout<<" ";
  cout<<s[count-i-3]<<endl;
  }
  for(int i=l-1;i<=count-l-2;i++)
  cout<<s[i];
  return 0;
}

這幾種方法沒有好壞之分,只要能夠正確輸出,具體行列值取多少是自由選擇的。題目只給了2種容易正確的樣例,需要學會自己挖掘,遍歷各種情況,找到多條正確的路中的一條即可。