Last active
January 31, 2018 06:11
-
-
Save wongsyrone/87af385b32594bb862cc987ca94650b0 to your computer and use it in GitHub Desktop.
PAT 打印沙漏
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
1027. 打印沙漏(20) | |
本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印 | |
***** | |
*** | |
* | |
*** | |
***** | |
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。 | |
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。 | |
输入格式: | |
输入在一行给出1个正整数N(<=1000)和一个符号,中间以空格分隔。 | |
输出格式: | |
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。 | |
输入样例: | |
19 * | |
输出样例: | |
***** | |
*** | |
* | |
*** | |
***** | |
2 | |
*/ | |
#include <stdio.h> | |
#include <math.h> | |
// matrix printing | |
int print(char ch, int numEachLine) { | |
int i; | |
int j; | |
int used = 0; | |
for (i = 0; i < numEachLine; i++) { | |
for (j = 0; j < numEachLine; j++) { | |
if (i+j > numEachLine -1 && i < j) continue; | |
else if (i+j < numEachLine-1 && i > j) printf(" "); | |
else { | |
printf("%c", ch); | |
used++; | |
} | |
} | |
printf("\n"); | |
} | |
return used; | |
} | |
int main() { | |
char ch; | |
int n; | |
scanf("%d %c", &n, &ch); | |
// minimum: 3*3 matrix with 7 symbols | |
if (n<7) { | |
printf("%d",n); | |
return 0; | |
} | |
// find max odd number | |
int upnum = ceil(sqrt(n)); | |
int numEachLine = ((upnum & 1 ) == 0) ? upnum - 1 : upnum; | |
//printf("numEachLine=%d\n", numEachLine); | |
int used = print(ch, numEachLine); | |
printf("%d", n-used); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment