1031. 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 lowoThat 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
题目的关键在于对n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N } with n1 + n2 + n3 - 2 = N的把握,题目之前一句提到要让U的形状越方越好,通过这个算式我们知道n2的范围是3到N,n1=n3,我们知道,n2越大,n1和n3救会越小,要让n1和n3最大,必须找到最小的满足条件的n2,这里的一个隐含条件是N
+ 2 - n2为偶数,也就是n1=n3所带来的条件,因此我们让n2从3到N变化,如果得到的N+2-n2是偶数,则再判断是否它的一半(k)满足小于等于n2,如果满足则已经找到合适的k,否则继续寻找,具体实现如下:
for(n2 = 3; n2 <= N; ++n2){ int temp = N + 2 -n2; if(temp%2 != 0) continue; n1 = temp/2; if(n1 <= n2) break; }在找到了k值之后,n1、n2、n3就确定了,下面只需要把输入的字符依次压入n1、n2、n3容器,然后按照题目的规则输出即可,这里使用的是vector<char>来容纳字符,具体代码如下:
#include <iostream> #include <string.h> #include <string> using namespace std; int main() { string input; string str1 = ""; string str2 = ""; string str3 = ""; int n1,n2,n3; int temp = 0; cin >> input; int N = input.length(); for(n2 = 3; n2 <= N; ++n2) { int temp = N + 2 -n2; if(temp%2 != 0) continue; n1 = temp/2; if(n1 <= n2) break; } n3 = n1; int i = 0; int offset = 0; for(i = 0; i < n1 - 1; i++){ str1.push_back(input[i + offset]); } offset += i; for(i = 0; i < n2; i++){ str2.push_back(input[i + offset]); } offset += i; for(i = 0; i < n3 - 1; i++){ str3.insert(str3.begin(),input[i + offset]); } for(int i = 0; i < n1 -1 ;i++){ cout << str1[i]; for(int j = 0; j < n2 -2; j++) cout << " "; cout << str3[i] << endl; } for(int i = 0; i < n2; i++){ cout << str2[i]; } cout << endl; return 0; }