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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章