B1027. 打印沙漏 (20)
Description:
本題要求你寫個程序把給定的符號打印成沙漏的形狀。例如給定17個“*”,要求按下列格式打印
***** *** * *** *****
所謂“沙漏形狀”,是指每行輸出奇數個符號;各行符號中心對齊;相鄰兩行符號數差2;符號數先從大到小順序遞減到1,再從小到大順序遞增;首尾符號數相等。
給定任意N個符號,不一定能正好組成一個沙漏。要求打印出的沙漏能用掉盡可能多的符號。
Input:
輸入在一行給出1個正整數N(<=1000)和一個符號,中間以空格分隔。
Output:
首先打印出由給定符號組成的最大的沙漏形狀,最後在一行中輸出剩下沒用掉的符號數。
Sample Input:
19 *
Sample Output:
*****
***
*
***
*****
2
1 #include <cstdio> 2 #include <cmath> 3 4 int main() 5 { 6 int n; 7 char c; 8 scanf("%d %c", &n, &c); 9 10 int bottom = (int)sqrt(2.0*(n+1))-1; 11 if(bottom%2 == 0) 12 --bottom; 13 int used = (bottom+1)*(bottom+1)/2-1; 14 for(int i=bottom; i>=1; i-=2) { 15 for(int j=0; j<(bottom-i)/2; ++j) printf(" "); 16 for(int j=0; j<i; ++j) printf("%c", c); 17 printf("\n"); 18 } 19 for(int i=3; i<=bottom; i+=2) { 20 for(int j=0; j<(bottom-i)/2; ++j) printf(" "); 21 for(int j=0; j<i; ++j) printf("%c", c); 22 printf("\n"); 23 } 24 printf("%d\n", n-used); 25 26 return 0; 27 }
A1031. Hello World for U (20)
Description:
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 n1characters, 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.
Input:
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:
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
1 #include <cstdio> 2 #include <cstring> 3 4 int main() 5 { 6 char str[100], ans[40][40]; 7 gets(str); 8 9 int N = strlen(str); 10 int n1 = (N+2)/3, n3 = n1, n2 = N+2-n1-n3; 11 for(int i=1; i<=n1; ++i) { 12 for(int j=1; j<=n2; ++j) 13 ans[i][j] = ' '; 14 } 15 16 int pos = 0; 17 for(int i=1; i<=n1; ++i) ans[i][1] = str[pos++]; 18 for(int j=2; j<=n2; ++j) ans[n1][j] = str[pos++]; 19 for(int i=n3-1; i>=1; --i) ans[i][n2] = str[pos++]; 20 for(int i=1; i<=n1; ++i) { 21 for(int j=1; j<=n2; ++j) 22 printf("%c", ans[i][j]); 23 printf("\n"); 24 } 25 26 return 0; 27 }
1 #include <cstdio> 2 #include <cstring> 3 4 int main() 5 { 6 char str[100]; 7 gets(str); 8 9 int N = strlen(str); 10 int n1 = (N+2)/3, n3 = n1, n2 = N+2-n1-n3; 11 for(int i=0; i<n1-1; ++i) { 12 printf("%c", str[i]); 13 for(int j=0; j<n2-2; ++j) 14 printf(" "); 15 printf("%c\n", str[N-i-1]); 16 } 17 for(int i=0; i<n2; ++i) 18 printf("%c", str[n1+i-1]); 19 20 return 0; 21 }