2013
12-13

# 九度-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.

There are multiple test cases.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.

For each test case, print the input string in the shape of U as specified in the description.

helloworld!
ac.jobdu.com

h   !
e   d
l   l
lowor
a    m
c    o
.    c
jobdu.

cpp 代码如下：
#include <iostream>
#include <string>

using namespace std;
void print(int n1, string str, int arrayLength, int n2) {
//打印结果
for (int i = 0; i < n1; i++) {
if (i == (n1 - 1)) {
cout << str.at(i);
for (int j = i + 1; j < arrayLength; j++) {
cout << str.at(j);
}
} else {
cout << str.at(i);
for (int j = 0; j < n2 - 2; j++) {
cout << " ";
}
cout << str.at(arrayLength - 1) << endl;
arrayLength--;
}

}

}

void getResult(int arrayLength, int& n1, int& n2) {
//进行求解
if (arrayLength >= 5 && arrayLength < 80) {
//获取n2 的最小结果
int minResult = (arrayLength + 2) / 3;
if ((arrayLength + 2) % 3 == 0) {
n1 = n2 = minResult;
} else {
for (n2 = minResult; n2 < arrayLength; n2++) {
for (n1 = n2 - 1; n1 > 0; n1--) {
if ((2 * n1 + n2 - 2) == arrayLength) {
//打印结果
return;
}
}

}

}

}

}

int main() {
//用于记录求解结果
int n1=0, n2=0;

string str;
//最小结果统计

//数组长度
int arrayLength;
while (cin >> str)
{
//cout<<str.length();
//获得数组的长度
arrayLength = str.length();
//进行求解
getResult(arrayLength, n1, n2);
print(n1,str,arrayLength,n2);
cout << endl;

}

return 0;

}
/**************************************************************
Problem: 1464
User: coder
Language: C++
Result: Accepted
Time:10 ms
Memory:1520 kb
****************************************************************/