HDU--1396--三角形递推

Given an equilateral triangle with n the length of its side, program to count how many triangles in it.

Input

The length n (n <= 500) of the equilateral triangle's side, one per line.

process to the end of the file

Output

The number of triangles in the equilateral triangle, one per line.

Sample Input
1
2
3
Sample Output
1
5
13

思路:a[n]=a[n-1]+1+2+...+n-1+n=a[n-1]+n*(n+1)/2;
递推:前三角形数+新增两层的三角形数+新增三层以上;

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int MAX=500+1;
long long f[MAX];
void init(){
	f[1]=1;
	for(int i=2;i<=MAX;i++){ 
		f[i]=f[i-1]+i*(i+1)/2;
		int k=i-1;
        while(k>0){
            f[i]+=k;
            k-=2;
		} 
	}
}
int main(){
	int n;
	init();
	while(scanf("%d",&n)!=EOF){
		printf("%lld\n",f[n]);
	}
}
发布了170 篇原创文章 · 获赞 73 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/104455027
今日推荐