一、题目描述
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:
二、解题思路
其实我认为在20分题中,这个题目还是有点复杂的。题目已经告诉了我们数量关系,第一列和第三列字符个数为 n 1 , n 3 n_1, n_3 n1,n3,最底下一行的字符数为 n 2 n_2 n2。根据样例我们可以看出, n 1 = n 3 n_1 = n_3 n1=n3,那么 n 1 n_1 n1可以表示为 n 1 = ( N − n 2 + 2 ) / 2 n_1 = (N - n_2 + 2)/2 n1=(N−n2+2)/2。所以我们可以从3开始遍历选取 n 2 n_2 n2,找到的 n 2 n_2 n2必须满足两个条件,一个是 ( N − n 2 + 2 ) (N-n_2+2) (N−n2+2)必须是偶数,还有一个就是 n 1 ≤ n 2 n_1 \leq n_2 n1≤n2。满足这两个条件的数中,我们要取最大的 n 1 n_1 n1。这里要注意一个小小的坑,就是每一次循环, n 1 n_1 n1都要初始化为一个很小的数,否则上一个循环的不符合条件的 n 1 n_1 n1就会沿用到这里,造成错误。
三、AC代码
#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn = 85;
int main()
{
char order[maxn][maxn];
fill(order[0], order[0]+maxn*maxn, ' ');
string str;
cin >> str;
int sze = str.size();
int n1, n2, cnt=0, maxk=0;
for(n2 = 3; n2<sze; n2++)
{
n1 = -1;//测试点5
if((sze+2-n2)%2 == 0)
n1 = (sze+2-n2)/2;
if(n1>maxk && n1<=n2) maxk = n1;
}
n1 = maxk;
n2 = sze+2-2*n1;
for(int i=0; i<n1-1; i++)
order[i][0] = str[cnt++];
for(int i=0; i<n2; i++)
order[n1-1][i] = str[cnt++];
for(int i=n1-2; i>=0; i--)
order[i][n2-1] = str[cnt++];
for(int i=0; i<n1; i++)
{
for(int j=0; j<n2; j++)
printf("%c", order[i][j]);
printf("\n");
}
return 0;
}