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

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[n]);
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值