数数小木块

数数小木块

时间限制: 3000 ms  |  内存限制: 65535 KB
难度: 1
描述

在墙角堆放着一堆完全相同的正方体小木块,如下图所示:


 

 因为木块堆得实在是太有规律了,你只要知道它的层数就可以计算所有木块的数量了。

现在请你写个程序 给你任一堆木块的层数,求出这堆木块的数量.

输入
第一行是一个整数N(N<=10)表示测试数据的组数)
接下来的n行 每行只有一个整数 ,表示这堆小木块的层数,
输出
对应每个输入的层数有一个输出,表示这堆小木块的总数量,每个输出占一行
样例输入
2
1
5
样例输出
1
35
来源
2008年小学生程序设计友谊赛试题
上传者

ACM_赵铭浩


问题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=260

问题分析:

先找出每层方块的次数,然后找出规律,计算每层的次数。

1 1
1+2 2
1+2+3 3
1+2+3+4 4
1+2+3+4+5 5


代码:

#include <iostream>  
#include <stdio.h>   
#include <string.h>  
#include <math.h>  
#include <vector>  
#include <queue>  
#include <stack>  
#include <map>  
#include <string>  
#include <algorithm>  
#include <iomanip>
#define MAX 1000 
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int num[MAX];
int layer[MAX];
void init(){
	memset(num,0,sizeof(num));
	memset(layer,0,sizeof(layer));
	int ans=0;
	for(int i=1;i<MAX;i++){
		layer[i]=layer[i-1]+i;
	}
	for(int i=1;i<MAX;i++){
		for(int j=1;j<=i;j++){
			num[i]+=layer[j];
		}
	}
}
int main(int argc, char** argv) {
	/*freopen("file/input.txt","r",stdin);
	freopen("file/output.txt","w",stdout);*/
	init();
	int n;
	scanf("%d",&n);
	while(n--) {
		int tmp;
		scanf("%d",&tmp);
		printf("%d\n",num[tmp]);
	}
	return 0;
}
优秀代码:

01. #include <stdio.h>
02. int main()
03. {
04. int n,t;
05. scanf("%d",&t);
06. while(t--)
07. {
08. scanf("%d",&n);
09. printf("%d\n",n*(n+1)*(n+2)/6);
10. }
11. }
优秀代码直接找出了层次和第i层以上的所有方块的关系。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值