uva11401(Triangle Counting)

Title effect: calculated from the 1,2,3, ..., 3 n different integers selected such that in their length may be formed as the number of sides of the triangle.

Idea: by a general method requires triple loop, the time complexity is O (n ^ 3), certainly timeout, mathematical methods can therefore be used to analyze the problem. The maximum side length of the triangle is provided are x c (x) th, the other two sides each having a length y, z, can obtain xy <z <x; x enumeration fixed y, count the number 0 + 1 + 2 + .. . + (x-2) = (x-1) (x-2) / 2. The above solution comprising a case where y = z, and otherwise forget twice. While in the case of y = z y from x / 2 + 1 to x-1 enum far there are (x-1) / 2 of inversely, so that c (x) = ((x -1) * (x-2) / 2- (x-1) / 2) / 2.

Can be obtained by the above analysis, the maximum side length not exceeding n number of triangles is f (n) = c (1 ) + c (2) + ... + c (n).

. 1 #include <stdio.h>
 2  Long  Long F [ 1000005 ], X;
 . 3  int main ()
 . 4  {
 . 5      int n-;
 . 6      F [ . 3 ] = 0 ;
 . 7      for (X = . 4 ; X <= 1000000 ; X ++ ) // off + recursive calculation 
. 8          F [X] = F [X- . 1 ] + ((X- . 1 ) * (X- 2 ) / 2 - (X- . 1 ) / 2 ) / 2 ;
 . 9      the while ( scanf ( "%d",&n)==1)
10     {
11         if(n<3) break;
12         printf("%lld\n",f[n]);
13     }
14     return 0;
15 }
View Code

 

Guess you like

Origin www.cnblogs.com/ljy08163268/p/11705837.html