UVA11401 Triangle Counting --- 递推

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/lmhlmh_/article/details/99678770

题目大意:计算从1,2,3,...,n中选出3个不同的整数,使得以它们为边长可以构成三角形的个数。

题解(蓝书p107):用一般的方法需要三重循环,时间复杂度为O(n^3),肯定超时,因此可用数学的方法对问题进行分析。设最大边长为x的三角形有c(x)个,另外两边长分别为y,z,则可得x-y<z<x;固定x枚举y,计算个数0+1+2+...+(x-2)=(x-1)(x-2)/2。上面的解包含了y=z的情况,而且其他情况算了两遍。而y=z的情况时y从x/2+1枚举到x-1为止有(x-1)/2个解,所以c(x)=((x-1)*(x-2)/2-(x-1)/2)/2。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
ll f[1000010];

int main() {
  f[3] = 0;
  for(int x = 4;x <= 1000000;x++) {
    f[x] = f[x-1] + ((ll)(x-1)*(x-2)/2-(x-1)/2) / 2;
  }

  int n;
  while(scanf("%d",&n) != EOF) {
    if(n < 3) break;
    printf("%lld\n",f[n]);
  }

  return 0;
}

猜你喜欢

转载自blog.csdn.net/lmhlmh_/article/details/99678770
今日推荐