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
-
上传者
思路:
常规思路是模拟
但是时间复杂度将会是(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]); } }
时间: 2024-11-26 02:00:58