HDU1396 Counting Triangles
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> #include<string.h> int main(){ long long a[505]; a[1]=1; for(int i=2;i<505;i++){ a[i]=a[i-1]+(2*i-1)+(i*(i-1))/2; int k=i-3; while(k>0){ a[i]=a[i]+k; k=k-2; } } int n; while(scanf("%d",&n)!=EOF){ printf("%lld\n",a[n]); } return 0; }
思路:
边长为n的三角形的个数=边长为(n-1)的三角形的个数+第n层新增的边长为1三角形的个数+边长大于1的三角形的个数+倒三角形的个数
a[n]=a[n-1]+(2*n-1)+(n*(n-1))/2+(n-3)+(n-5)+直到n为0停止
a[1]=1,a[2]=5,a[3]=13,a[4]=27,a[5]=48,
a[4]=13+7+6+1
a[5]=27+9+10+2
a[6]=48+11+15+3+1