UVA 11401 - Triangle Counting

Problem G
Triangle Counting

Input: Standard Input

Output: Standard Output

 

You are given n rods of length 1, 2…, n. You have to pick any 3 of them & 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.

 

Input

 

The input for each case will have only a single positive integer (3<=n<=1000000). The end of input will be indicated by a case with n<3. This case should not be processed.

 

Output

 

For each test case, print the number of distinct triangles you can make.

 

Sample Input                                                  Output for Sample Input

5

8

0

3

22

 


Problemsetter: Mohammad Mahmudur Rahman


解题思路,分段法,f [n] 记录最长的那条边不超过n的放法数, 假设c[n] 为最长边为n的放法数  f [n] = f [n-1] + c[n] 。


假设最长边为z,其它为 x,y;

则   z-x < y < z

当  x=1 时, z-1<y<z  0 种方案,

当  x=2 时, z-2<y<z  1 种方案,

......................................................

当  x=z-1时, 1<y<z  z-2种方案

所以总计 (z-1)*(z-2)/2 种方案

但是其中包含了x与y想等的情况,因为 x取值为 [ z/2+1 , z-1 ] 区间内可能 x,y相等,共 (z-1)- (z/2+1)+1=z/2-1 种方案

而且x,y与 y,x认为为两个,重复计算了,所以除以2

所以 c[n]= [ (z-1)*(z-2)/2 -(z/2-1) ] / 2


#include <iostream>
using namespace std;

const int maxn=1000000;
unsigned long long f[maxn+10];
int n;

void ini(){
	f[3]=0;
	for(long long z=4;z<=maxn;z++){
		f[z]=f[z-1] + ( (z-1)*(z-2)/2 - (z/2 -1) )/2;
	}
}

int main(){
	ini();
	while(cin>>n && n>=3){
		cout<<f[n]<<endl;
	}
	return 0;
}


转载于:https://www.cnblogs.com/toyking/p/3797375.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值