@送给即将打天梯赛志同道合的朋友们
题目精述分析:这一道题说实话是一道水题,按要求格式输出即可,但是为了寻求更为简便的方法,减少不必要的分类讨论,我们可以在打印的基础上先进行一定的数学分析。不仅仅可以减少代码量,也可以很好的锻炼思维。
输入要求:输入一个整数和一个字符。
输出要求:输出格式图形和多余的未使用的字符个数(最大程度的利用所给字符)
分析:我们很容易观察到对于输入限定的字符个数n和行数x之间存在着相应的联系:
x = (int) ( sqrt( (n + 1) / 2) );
那么我们也很容易计算出剩余last的字符有多少个
last = n - 2 * x * x + 1;
再来分析一下第一行的字符个数与x之间存在的联系:
begin = 2 * x - 1;其中这个begin也就决定了我们输出的图形有多少行;
再来考虑每行的字符temp和空格blank的输出,
很容易发现temp = begin - 2 * (i - 1);
这里我们还需要注意的是对于沙漏的上半部分上面的计算式子为正数,而对于下半部分确为负数,取它的绝对值即可
前缀空格blank = (begin - temp)/ 2;
之后我们只需要用两个while或者for来实现输出即可。
直接上代码部分:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <iomanip>
#include <math.h>
using namespace std;
#define FOR(i, a, b) for(int i = a; i <= b; i++)
#define ROF(i, a, b) for(int i = a; i >= b; i--)
#define mst(a) memset(a, 0, sizeof(a))
#define mstn(a, n) memset(a, n, sizeof(a))
typedef long long ll;
int n;
int x;
int last;
int beg;
char ch;
int main()
{
scanf("%d %c", &n, &ch);
x = sqrt((n + 1) / 2);
last = n - 2 * x * x + 1;
beg = 2 * x - 1;
FOR(i, 1, beg + 1)
{
int temp = beg - 2 * (i - 1);
if (temp == -1)
continue;
else
temp = abs(temp);
int blank = (beg - temp) / 2;
while (blank--)
printf(" ");
while (temp--)
putchar(ch);
printf("\n");
}
printf("%d\n", last);
system("pause");
return 0;
}
第一次写文章~~~