思路:把每个完整的沙漏的数目存在sum数组中,然后用upperbound 找到第一个比输入的n的大的数的下标,然后把这个下标用公式转换为对应的要打印的第一行的*的数目,然后打印就好了。之所以这样是为了提前把数目算好,避免每个测试样例都使用sqrt函数 这个函数比较费时,所以这样做就可以 省时,提高效率。这是常用的技巧,在素数筛法中用过这种办法。
下来介绍upper_bounder和lower_bounder这两个函数。
在c c++ java 中都有这个函数。
upper_bound( begin,end,num);begin end 都是指针,num是你的数组元素类型。 返回的是地址,因此用指针变量接收。
第一种目的 需要查找的内容。
int *p = NULL;
p = upper_bound(begin,end,num);
int k = *p;
*p即那个数字。
第二种目的 需要查找的那个元素的下标
int p = upper_bound(begin,end,num) -num; 这次用int类型接收。
这个方法也可以用重写的cmp方法,可以用来比较struct 那种类型的。但是我不太会用。所以就可以把struct中的元素转到一个数组中,然后用这个数组去找,再转换下标就可以了。
题目:
时间限制 1000 ms 内存限制 32768 KB 代码长度限制 100 KB 判断程序 Standard (来自 小小)
题目描述
本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
*
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递
增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入描述:
输入在一行给出1个正整数N(<=1000)和一个符号,中间以空格分隔。
输出描述:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
输入例子:
19 *
输出例子:
*
2
代码如下:
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <math.h>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
const int Max = 110;
/*typedef struct {
int posit;
int sum1;
}Sum;*/
int sum[Max];
int Size = 0;
void chushi() {
for (int i = 1; i < Max; i+=2) {
//sum[i] = (()* ((i + 1) / 2);
sum[Size++] = ((i + 1) / 2)* ((i + 1) / 2) *2 -1;
}
return;
}
void print1(int nc,char cc) {
for (int i = 0; i < nc; i+=2) {
for (int j = 0; j < i/2; j++) {
printf(" ");
}
for (int k = 0; k < (nc - i); k++) {
printf("%c", cc);
}
for (int j = 0; j < i/2; j++) {
printf(" ");
}
printf("\n");
}
return ;
}
void print2(int nc,char cc){
for (int i = 0; i < nc-2; i += 2) {
for (int j = 1; j < (nc - i)/2; j++) {
printf(" ");
}
for (int k = 0; k < (i +1+2); k++) {
printf("%c", cc);
}
for (int j = 1; j < (nc - i) /2; j++) {
printf(" ");
}
printf("\n");
}
return;
}
int main()
{
freopen("Text.txt", "r", stdin);
int n = 0;
char c = ' ';
chushi();
while (scanf("%d %c ",&n,&c)!=EOF ) {
int pos = 0;
pos= upper_bound(sum,sum + Size -1, n) - sum;
int pos1 = pos;
pos = (pos -1) * 2 + 1;
print1(pos, c);
print2(pos, c);
printf("%d\n",n -sum[pos1 - 1]);
}
return 0;
}