原题干:
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
题目大意: 给定一个字符串,要求将这个字符串按照U形输出
但是要保证左侧的字符数小于等于底部的字符数,找到满足这个条件的最大侧边字符数。
这种输出图案的题目,画几个找找规律就好了。
把10~~13个字符的字符串都画一遍,就会发现侧边字符数量等于(总长度+2) / 3
这样就可以知道底部字符数量是总数量+2-2*侧边数量
接着循环输出就好啦。
代码很简单,不做过详细的解释。:
#include <iostream>
#include <string>
using namespace std;
int main(){
string input;
cin >> input;
int len = input.length();
int side = (len + 2) / 3;
int buttom = len + 2 - (2 * side);
for(int i = 0; i < side - 1; i++){
cout << input[i];
for(int j = 0; j < buttom - 2; j++) cout << ' ';
cout << input[len - 1 - i];
cout << endl;
}
for(int i = side - 1; i < side + buttom - 1; i++)
cout << input[i];
cout << endl;
return 0;
}