题意:从1~n中选出3个整数,使得他们三边能组成三角形,给定一个n,问能组成多少个不同的三角形?
题解:n最大能达到1000000,所以只能用O(n)来解决。
设最大边为x的三角形个数为C(x),y+z>x , x-y<z<x,当y=1时 z无解,y=2,z一个解……y=x-1,z有x-2个解
所以0+1+2+……+x-2=(x-1)(x-2)/2,但是里面有y=z的情况,有x/2-1种。
而且里面每个三角形重复了2遍,所以c(x)=((x-1)*(x-2)/2-(x/2-1))/2,
f[x]=f[x-1]+((x-1)*(x-2)/2-(x/2-1))/2。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <iterator>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cctype>
using namespace std;
#define si1(a) scanf("%d",&a)
#define si2(a,b) scanf("%d%d",&a,&b)
#define sd1(a) scanf("%lf",&a)
#define sd2(a,b) scanf("%lf%lf",&a,&b)
#define ss1(s) scanf("%s",s)
#define pi1(a) printf("%d\n",a)
#define pi2(a,b) printf("%d %d\n",a,b)
#define mset(a,b) memset(a,b,sizeof(a))
#define forb(i,a,b) for(int i=a;i<b;i++)
#define ford(i,a,b) for(int i=a;i<=b;i++)
typedef long long LL;
const int N=1100001;
const int M=6666666;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-7;
LL f[N];
int main()
{
f[3]=0;
for(LL x=4;x<=1000000;x++)//这个地方要注意x要为longlong
f[x]=f[x-1]+((x-1)*(x-2)/2-(x/2-1))/2;
int n;
while(si1(n)&&n>=3)
{
printf("%lld\n",f[n]);
}
return 0;
}