Find triangle (recursive)

UVA 11401

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2396

Solution: seeking the number of triangles these numbers from 1 to n can be constituted.

Suppose now that the number is x, in front of it to find the two numbers y and z satisfy the triangle defined, there are x - y <z <x.

When y = 1, z satisfies not the number of x - 1 <z <x, the number of triangles is 0 num;

When y = 2, z is 1 satisfies x - 2 <z <x, num = 1;

y = 3, num = 2;

······

y = x - 1, n = x - 2;

The total number of triangles may be formed as a arithmetic sequence, N = (x - 2) * (x - 1) / 2;

but! Note that, in the triangle, comprising a case where y == z, and each triangle is counted twice (the result is divided by 2 as long as the problem is solved, where the key is to find the y == z);

The value of y from x / 2 + 1 begins to x - 1 with a (x - 1) - (x / 2 + 1) + 1 = x / 2 - 1 of inversely, the solution is x / 2 when x is an odd number, solution is x / 2 is an even number - 1, so to avoid the parity judgment, we put it into (x - 1) / 2 alone.

Code:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<stack>
#define ll long long
using namespace std;

const ll N = 1000005;
const ll maxn = 1e18;
const int inf = 1e9;

ll a[1000010];

int main()
{
    a[3] = 0;//预处理 
    for(ll i = 4; i <= 1000000 ; I ++ ) 
        A [I] = A [I- . 1 ] + ((I- . 1 ) * (I- 2 ) / 2 - (I- . 1 ) / 2 ) / 2 ; 
        
    int n-;
     the while ((Scanf ( " % D " , & n-))! = the EOF && n-> = . 3 ) // Note here must n> = 3 in order to lead, n! = 0 not pass 
    { 
        the printf ( " % LLD \ n- " , A [n-] ); 
    } 
    return  0 ; 
}

 

Guess you like

Origin www.cnblogs.com/xiaohanghuo/p/11360480.html