hdu Counting Triangles

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
View Code
 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string.h>
 4 using namespace std;
 5 int main()
 6 {
 7     int n;
 8     while(~scanf("%d",&n))
 9     {
10         int d[5];
11         d[0]=0;
12         d[1]=1;
13         d[2]=5;
14         d[3]=13;
15         if(n<=3)
16         {
17             printf("%d\n",d[n]);
18             continue;
19         }
20         int i;
21         for(i=4;i<=n;i++)
22         {
23             d[4]=d[3]+2*i-1+(i*i-i)/2;
24             if(i%2==0)
25                 d[4]=d[4]+(i-3+1)*(i-2)/4;
26             else
27                 d[4]=d[4]+(i-3)*(i-1)/4;
28             d[3]=d[4];
29         }
30         printf("%d\n",d[4]);
31     }
32     return 0;
33 }
34 
35 
36         

递推题,想法如下:

首先知道了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;

详细有代码……

posted @ 2012-10-06 16:27  欧阳生朵  阅读(371)  评论(0编辑  收藏  举报