您的位置:首页 > 其它

数学:给你长度1~n的线段 组成三角形最长边长度不超过你的n三角形有多少个

2015-03-05 16:48 295 查看


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


来源UVA
上传者
TC_李远航
思路:
常规思路是模拟
但是时间复杂度将会是(o^3)明显超时
所以我们猜一定是有规律的,从数学角度开始分析
设三角形最长边为x,(其他y,z) 最多有c(x)个三角形
那么y+z>x
x-y<z<x
所以当y=1是误解0 y=2 一个解 y=3 三个解.....
0+1+2+3+....+(x-2)
总共:(x-2)*(x-1)/2
但是这里计算了y=z的情况而且每个三角形算了两次
(y=z的情况) y=x/2+1开始 (x-1)-(x/2+1)+1=x/2-1 不难发现x为奇数情况是x/2 偶数情况是x/2-1 so→(技巧)(x-1)/2避免奇偶讨论
于是 c(x)=((x-1)(x-2)/2-(x-1)/2)/2
题目问题的是最长边长不超过n的三角形有多少个 so F(n)=F(n-1)+c(n);
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
long long a[1000005];
int main()
{
int n;
a[1]=a[2]=a[3]=0;
for(long long i=4;i<1000005;i++)
a[i]=a[i-1]+((i-1)*(i-2)/2-(i-1)/2)/2;
while(~scanf("%d",&n))
{
if(n<=0)
break;
printf("%lld\n",a
);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐