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;

详细有代码……

转载于:https://www.cnblogs.com/ouyangduoduo/archive/2012/10/06/2713068.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值