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

输入
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.

输出
For each test case, print the input string in the shape of U as specified in the description.

样例输入

helloworld!

样例输出

h   !
e   d
l   l
lowor

思路:

n1和n3是左右两条竖线从上到下的字符个数,n2是底部横线从左到右的字符个数。

题目中给了公式n1 + n2 + n3 – 2 = N,并且我们可以知道n1=n3,n1<=n2,在满足上述条件下n1要最大。

令N=字符串长度+2,进行分类讨论:

  1. 如果N % 3 == 0,n正好被3整除,直接n1 == n2 == n3;
  2. 如果N % 3 == 1,因为n2要比n1大,所以把多出来的那1个给n2
  3. 如果N % 3 == 2, 就把多出来的那2个给n2
    所以得到公式:n1 = N / 3,n2 = N / 3 + N % 3

即步骤为:

1.计算字符串长度l;

2.计算两边的字符数n1= N / 3;

3.计算最后一行中间的字符数(前面每行中间的空格数)space=n2-2;

4.输出每行相应的字符。

#include <iostream>

using namespace std;

int main()
{
    int i,j,n1,l,cnt=0,n2;
    string s;
    while(cin>>s){
        l=s.length();
        n1=(l+2)/3;
        n2=n1+(l+2)%3;
        for(i=1;i<n1;i++){
            cout<<s[cnt];
            for(j=1;j<=n2-2;j++){
                cout<<" ";
            }
            cout<<s[l-cnt-1]<<endl;
            cnt++;

        }
        for(i=cnt;i<cnt+n2;i++){
            cout<<s[i];
        }
    }

    return 0;
}