「Uva11401」数三角形

Problem

pdf

Description

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.

Input

The input for each case will have only a single positive integer n (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

5
8
0

Sample Output

3
22

Solution

思路

显然对于每一个三角形,设其三边为\(x,y,z(最长边)\),则有\(x+y>z\),\(x-y<z\),所以\(z-y<x<z\).
然后y的取值范围为1~n-1,那么此时可以得到,当y=1时,x无解;当y=2时,x有1个解;当y=z-1时,x有z-2个解
所以递推式就很容易求

Code

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<queue>
#define ll long long
#define re register
using namespace std;
inline int gi(){
    int f=1,sum=0;char ch=getchar();
    while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0' && ch<='9'){sum=sum*10+ch-'0';ch=getchar();}
    return f*sum;
}
ll f[1000010];
int main(){
    int j,k,n,m;
    f[3]=0;
    for(ll i=4;i<=1000000;i++)
        f[i]=f[i-1]+((i-1)*(i-2)/2-(i-1)/2)/2;
    while(scanf("%d",&n)==1 && n>=3)
        printf("%lld\n",f[n]);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/cjgjh/p/9426740.html