1031 Hello World for U (20 分)
1. 題目
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 n
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
2. 題意
將一串字串以U
型形式輸出出來。
3. 思路——字串
根據題意計算n1,n2,n3,這裡n1等於n3,只要定義n1和n2即可。
計算方法:
已知:n1=n3=max {k | k≤n2 for all 3≤n2≤N },且n1+n2+n3-2=N
可得:\(n1=n3=(N+2)/2\)(結果向下取整)
\(n2=N+2-n1-n3\)
計算出n1和n2後,即可根據題目要求輸出U
型圖形(見程式碼)。
4. 程式碼
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
int n1, n2;
int N = str.length();
n1 = (N + 2) / 3;
n2 = N + 2 - (2 * n1);
for (int i = 0; i < n1 - 1; ++i)
{
// 輸出第i個字元
cout << str[i];
// 輸出中間的空格
for (int j = 0; j < n2 - 2; ++j) cout << " ";
// 輸出倒數第i+1個字元
cout << str[N - 1 - i] << endl;
}
// 最後一行輸出剩下的中間字串
cout << str.substr(n1 - 1, n2) << endl;
return 0;
}