問題 B: Hello World for U
時間限制: 1 Sec 內存限制: 32 MB
題目描述
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.
輸入
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.
輸出
For each test case, print the input string in the shape of U as specified in the description.
樣例輸入
helloworld!
樣例輸出
h !
e d
l l
lowor
提示
這一題需要解決的問題是將一個字符串寫成U字形。拿到這一題的第一映像是U字的寫法(可沒有茴香豆的“茴”寫法多),先是寫第一排第一個字符,然後寫第二排第一個字符……然後是最後一排,然後是倒數第二排……但在C語言中如果我們要這樣寫U字形的字符串就需要在數組中操作了。如果是直接輸出的話,那隻能自上至下一行一行輸出。首先是第一行,寫出第一個字符和最後一個字符,第二行寫出第二個字符和倒數第二個字符……最後是最後一行。需要注意的是除了最後一行輸出所有字符,前面每一行只輸出兩個字符。中間還有空格來隔開每行的兩個字符(具體有多少空格,待會計算)。
思路有了,看看具體的要求。字符串的長度是N,n1,n3代表兩邊每列字符的數目。n2代表最後一行的字符數。題目中給了一個算式:
n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N } with n1 + n2 + n3 - 2 = N.
仔細研究這個算式,這裏的k是不大於n2的,也就是說n1和n3是不大於n2且滿足n1+n2+n3=N+2的最大值。那麼自然有n1=n3=(N+2)/3,n2=N+2-(n1+n3)。也就是說設side爲兩邊的字符數(包括最後一行的兩端),則side=n1=n3=(N+2)/3。設mid爲最後一行除去兩端的兩個字符後剩下的字符數,mid=N-side*2(總長度減去兩邊的字符數)。同時mid也是我們輸出除最後一行外前面所有行需要空出的空格數。
最後如何在第一行輸出第一個字符和最後一個字符呢?那自然是str[0]和str[len-1-i](len爲字符串的長度,也就是N)。
於是問題完美解決,步驟如下:
1)計算字符串長度len;
2)計算兩邊的字符數side=(len+2)/3;
3)計算最後一行中間的字符數(前面每行中間的空格數);
4)輸出每行相應的字符。
由於該題目不難,也沒有什麼需要特別注意的,我也就不寫注意點了。具體細節詳見參考代碼。
經驗總結
震驚!題目裏竟然自帶解析!那我偷個懶啦~~(沒記錯的話應該是PAT乙級的一道題目~~)
AC代碼
#include <cstdio>
#include <cstring>
int main()
{
char s[90];
while(scanf("%s",s)!=EOF)
{
int n;
n=strlen(s);
int side=(n+2)/3;
int mid=n-side*2;
for(int i=0;i<side-1;i++)
{
printf("%c",s[i]);
for(int j=0;j<mid;j++)
printf(" ");
printf("%c\n",s[n-1-i]);
}
for(int i=side-1;i<side+mid+1;i++)
printf("%c",s[i]);
memset(s,'\0',sizeof(s));
}
return 0;
}