九度 1464:Hello World for U

题目描述:

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.

 

思路

1. N1+N2+N3-2= N, 尽量追求 N1,N2,N3 平均, 所以要么取 N3 = ceil((N+2)/3), 要么取 N1=N2=(N+2)/3-1. 第一种取法有不适合的情况

 

代码

#include <iostream> #include <stdio.h> #include <string> #include <math.h>
using namespace std; int n1, n2, n3; int main() { string input; while(cin >> input) { int len = input.size(); n1 = n2 = (len+2)/3 -1; n3 = len - 2*n1; for(int i = 0; i < n1; i ++) { cout << input[i]; for(int j = 0; j < n3-2; j ++) { cout << ' '; } cout << input[len-i-1]; cout << endl; } for(int i = 0; i < n3; i ++) { cout << input[i+n1]; } cout << endl; } return 0; }

 

你可能感兴趣的:(Hello world)