hdu 1396 Counting Triangles(递推)

时间:2023-03-09 02:42:26
hdu 1396 Counting Triangles(递推)

Counting Triangles

Problem Description

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

Input

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



process to the end of the file

Output

The number of triangles in the equilateraltriangle, one per line.

Sample Input

1

2

3

Sample Output

1

5

13

/*****************************************

数三角形的个数,开始忽略了顶角在最后一排的倒着的那些三角形,老是WA,然后怎么数都不对,后来看了别人的博客,我数的方式不对,

正确数的方式::假设边长为n

先数正向的三角形

1+2+3+......+(n-1)+n     ————(边长为1的三角形)

1+2+3+......+(n-2)+(n-1)     ————(边长为2的三角形)

1+2+3+......+(n-3)+(n-2)     ————(边长为3的三角形)

…………

1+2+3                      ————(边长为n-2的三角形)

1+2                      ————(边长为n-1的三角形)

1  ————(边长为n的三角形)

然后数倒着的三角形

当n为偶  /  奇  数时:1+2+3+……+(n-1)  ————(边长为1的三角形)

1+2+3+……+(n-3)  ————(边长为2的三角形)

1+2+3+……+(n-5)  ————(边长为3的三角形)

…………

1+2+3    ————(边长为   (n-2)/2   的三角形)

1————(边长为   n/2   的三角形)                     1————(边长为2的三角形)    最后一行注意,n为偶数  则+1  ,,n为奇数  则  + (1+2)

******************************************************/

#include <iostream>
using namespace std;
int num[1000];
void cal()
{
num[1] = 1;int i;
for(i = 2;i<500;i++)
num[i] = num[i-1]+i;
}
int main()
{
cal();
int n,i,sum;
while(cin>>n&&n)
{
sum = n*(n+1)*(n+2)/6;
n-=1;
while(n>0)
{
sum+=num[n];
n-=2;
}
cout<<sum<<endl;
}
return 0;
}