Problem Description
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
递推题,想法如下:
首先知道了D(1)=1,D(2)=5,D(3)=13;
在手动推出D(4)=27,D(5)=48,然后 不难发现,D(n)=D(n-1)+X,
而这里的X还不确定,根据画出来的图可以看出,当n=4时,D(4)=D(3)+4*2-1+3+2+1+1,
D(5)=D(4)+5*2-1+4+3+2+1+2;
看出规律后,试着假设D(6)=D(5)+6*2-1+5+4+3+2+1+3,
可是画图发现,最后面加的那个数不是3,而是4,即:D(6)=D(5)+6*2-1+5+4+3+2+1+4,
也就是说,D(6)=D(5)+6*2-1+5+4+3+2+1+3+1;
而D(5)=D(4)+5*2-1+4+3+2+1+2+0;
继而再一次假设,当n为偶数时,有D(n)=D(n-1)+n*2-1+(n-1)+(n-2)+…+1+(n-3)+(n-5)+..+1;
当n为奇数时,D(n)=D(n-1)+n*2-1+(n-1)+(n-2)+…+1+(n-3)+(n-5)+..+0;
详细有代码……
代码:
#include <iostream>
#include <cstdio>
using namespace std;
int ans[510];
int main()
{
int n, i, j;
ans[1] = 1;
for(i = 2; i <= 500; i++)
{
ans[i] = ans[i-1] + i*(i+1)/2;
for (j = i-1; j > 0; j-=2)
{
ans[i] += j;
}
}
while(~scanf("%d", &n))
{
cout << ans[n] << endl;
}
}