首页 > 代码库 > Hello World for U (20)

Hello World for U (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 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.

 

 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 #include <iostream>  2   3 #include <string>  4   5 using namespace std;  6   7    8   9 int main() 10  11 { 12  13   14  15       string ss; 16  17       while(cin>>ss) 18  19       { 20  21          int x,y; 22  23        bool u=false; 24  25          for(x=ss.length();x>=1;x--) 26  27          { 28  29              if(x<3) 30  31                { 32  33                      for(y=3;y<=ss.length();y++) 34  35                            if(2*x+y-2==ss.length()) 36  37                            { 38  39                               u=true; 40  41                                 break; 42  43                            } 44  45                } 46  47                   else 48  49                   { 50  51                         for(y=x;y<=ss.length();y++) 52  53                            if(2*x+y-2==ss.length()) 54  55                            { 56  57                               u=true; 58  59                                 break; 60  61                            } 62  63   64  65                   } 66  67               if(u)  break; 68  69   70  71          } 72  73   74  75   76  77          int i=0;int j=ss.length()-1;int k; 78  79        int tem=x-1; 80  81          while(tem--) 82  83          { 84  85             cout<<ss[i++]; 86  87               for(k=0;k<y-2;k++)  cout<<" "; 88  89           cout<<ss[j--]; 90  91               cout<<endl; 92  93          } 94  95   96  97          for(k=i;k<=j;k++) 98  99                cout<<ss[k];100 101          cout<<endl;102 103       }104 105   return 0;106 107 }
View Code

 

Hello World for U (20)