Triangle Counting
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
You are given n rods of length 1, 2…, n. You have to pick any 3 of them and build a triangle. How many distinct triangles can you make? Note that, two triangles will be considered different if they have at least 1 pair of arms with different length.
-
输入
- The input for each case will have only a single positive integer n(1<=n<=1000000). The end of input will be indicated by a case with n<1. This case should not be processed. 输出
- For each test case, print the number of distinct triangles you can make. 样例输入
-
5 8 0
样例输出
-
3 22
数学题找规律;
根据三角形三遍关系 ,令x表示最大边,则x-y<z<x
当y=2时, 一个解,x-1;
y=3时,两个解,x-2,x-1
y=4时,三个解,x-3,x-2,x-1
。。。。。。
y=x-1时,(x-2)个解,1,2 。。。。x-1
等差数列求和,(x-2+1)(x-2)/2
但是其中有y==z,x<y+z,dang y==z时,有x<2*y,x/2<y,所有相等的个数有(x-1)/2个
但是去掉等腰三角形之后 能发现剩下的三角形都存在两两重复的情况,因此还要除以2;
p【i】=p【i-1】+((x-1)*(x-2)/2-((x-1)/2)/2;
code:
#include<stdio.h>
#include<math.h>
long long p[1000001];
void init()
{
p[0]=p[1]=p[2]=p[3]=0;
for(long long i=4;i<1000001;i++)
p[i]=p[i-1]+((i-2)*(i-1)/2-(i-1)/2)/2;
}
int main()
{
int t;
init();
while(~scanf("%d",&t))
{
if(t<1)
break;
printf("%lld\n",p[t]);
}
return 0;
}