nyoj 982

来源:互联网 发布:潍坊网络招聘 编辑:程序博客网 时间:2024/06/05 02:49

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.
样例输入
580
样例输出
3

22


解题思路:这道题目的题意很简单,给出n条线段,长度为1-n,问有多少种方法可以从这n条线段中取出3条不同的线段,使得以它们为三边长可以组成三角形。这是一个纯数学推理问题。我们首先假设最大边为x,其余两边为y,z那么有不等式y+z>x。那么z的范围是x-y<z<x,接下来的工作就是枚举y的范围,然后看z能够取多少。

假设C(x)为最大边为x时,能得到的三角形个数,假设y从1-(x-1)枚举一遍,那么z所能取到的个数分别为0,1,2,......,x-2;所以总共有(x-1)(x-2)/2个,但是还没完,题目中的三条边都不能相等,但这里面出现了y=z的情况,所以要将这种情况去掉,并且每个三角形重复了一次,所以最后还要除以2。。要保证y=z的情况出现,那么y只能从最小的x/2+1开始,一直到x-1为止,总共出现了(x-1)-(x/2+1)+1=x/2-1,考虑到x的奇偶性,有 (x-1)/2个y=z的情况出现。。那么C(x)=((x-1)*(x-2)/2-(x-1)/2)/2。f(n) = C(1)+C(2)+......+C(n) = f(n-1)+C(n)。。

AC:

#include<iostream>using namespace std;long long f[1000005];int main(){f[1] = f[2] = f[3] = 0;for(int i = 4; i <= 1000000; i++)f[i] = f[i-1] + ((i-1)*(i-2)/2 - (i-1)/2)/2;int n;while(cin>>n){if(n < 1) break;cout<<f[n]<<endl;}return 0;}


0 0
原创粉丝点击