322
N line segments with a length of 1-n are given. How many methods can be used to retrieve 3 different line segments from the n line segments, so that they can form triangles with three sides of length.
Analysis: the first method is triplicate loop enumeration, but the time complexity is O (n ^ 3. Even algorithms with O (n ^ 2) time are difficult to handle, so mathematical analysis is required.
There are C (x) triangles with the maximum side length x, y and z For the other two sides, and y + z> x for the triangle inequality. Therefore, the z range is x-y <z <x.
According to this inequality, when y = 1, the X-1 <z <x, no solution; y = 2 there is a solution (z = x-1 ); y = 3 There are two solutions (z = X-1 or z = X-2 )...... Until y = X-1 has a X-2 solution. A total of 0 + 1 + 2 + ...... + (X-3) + (X-2) = (x-1) (X-2)/2 solutions.
But this is not the correct value of C (x), because the above solution contains the case of y = z, and each triangle is calculated twice. Therefore, we need to calculate the condition of y = z. The value of y starts from x/2 + 1 to X-1, a total of (x-1)-(x/2 + 1) + 1 = x/2-1, however, when x is an odd number, the value of y is x/2. If x is an even number, the value of y is x/2-1. So to avoid discussing the parity of x, we can write x/2-1 as (x-1)/2 without affecting the correct results. Deduct this decomposition, and then divide it by 2, that is, C (x) = (x-1) (X-2)/2-(x-1)/2)/2; the original question requires "the maximum side length cannot exceed n of the number of triangles F (n)", then F (n) = C (1) + C (2) +... + C (n ). The recursive formula is f (n) = F (n-1) + C (n ).
#include
long long ans[1000005];int main(){ ans[1] = ans[2] = ans[3] = 0; for(long long x = 4; x <= 1000000; x++) ans[x] = ans[x-1] + ((x-1)*(x-2)/2 - (x-1)/2) / 2; int n; while(~scanf("%d",&n)) { if(n < 1) break; printf("%lld\n",ans[n]); } return 0;}