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种容易正确的样例,需要学会自己挖掘,遍历各种情况,找到多条正确的路中的一条即可。

猜你喜欢

转载自blog.csdn.net/yi976263092/article/details/81001324