NYOJ 982 Triangle Counting (数学题)

Triangle Counting

时间限制: 1000 ms  |  内存限制: 65535 KB
描述
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

题目大意:给出n条线段,长度为1-n,问有多少种方法可以从这n条线段中取出3条不同的线段,使得以它们为三边长可以组成三角形。

分析:首先想到的方法就是三重循环枚举,但是时间复杂度为O(n^3),肯定超时。数据规模即使是O(n^2)时间的算法都很难承受,所以要进行数学分析。

设最大边长为x的三角形有C(x)个,另外两条边长分别为y和z,根据三角不等式有y+z>x。所以z的范围是x-y < z < x。

根据这个不等式,当y=1时x-1 < z < x,无解;y=2时有一个解(z=x-1);y=3时有两个解(z=x-1或者z=x-2)……直到y=x-1时有x-2个解。根据等差数列求和公式,一共有0+1+2+……+(x-3)+ (x-2) = (x-1)(x-2)/2个解。

可这并不是C(x)的正确值,因为上面的解包含了y=z的情况,而且每个三角形算了两遍。所以要统计出y=z的情况。y的取值从x/2+1开始到x-1为止,一共有(x-1) - (x/2+1) + 1 = x/2 - 1个,但是我们不难发现,当x为奇数时,y的取值为x/2个;x为偶数时,y的取值为x/2-1个。所以为了避免讨论x的奇偶性,我们把x/2-1写成(x-1)/2就可以了,而且不影响正确结果。把这分解扣除,然后在除以2,即C(x)=((x-1)(x-2)/2 - (x-1)/2)/2;原题要求的是"最大边长不超过n的三角形数目F(n)",则F(n)=C(1)+C(2)+…+C(n)。写成递推式就是F(n) = F(n-1) + C(n)。

#include<stdio.h>
long long ans[1000005];
int main()
{
    ans[1] = ans[2] = ans[3] = 0;
    for(long long x = 4; x <= 1000000; x++)
        ans[x] = ans[x-1] + ((x-1)*(x-2)/2 - (x-1)/2) / 2;
    int n;
    while(~scanf("%d",&n))
    {
        if(n < 1) break;
        printf("%lld\n",ans[n]);
    }
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值