Number of triangles attainable with given lengths of sticks that are powers of two

Given an array of N integers the place arr[i] denotes the variety of sticks of size 2i. The process is to seek out the variety of triangles attainable with given lengths having space ≥ zero.
Note: Every stick can solely be used as soon as.

Examples:

Input: a[] = 1, 2, 2, 2, 2
Output: three
All attainable triangles are:
(20, 24, 24), (21, 23, 23), (21, 22, 22).

Input: a[] = three, three, three
Output: three

Approach: The predominant commentary is that the triangles with space ≥ zero can solely be shaped if there are three identical lengths of sticks or one totally different and two comparable lengths of sticks. Hence greedily iterate from the again and rely the variety of pairs of identical size sticks out there which is arr[i] / 2. But if there’s a stick remaining, then a pair and a stick is used to type a triangle. In the tip, the whole variety of sticks left is calculated which is 2 * pairs and the variety of triangles that may be shaped with these remaining sticks can be (2 * pairs) / three.

Below is the implementation of the above strategy:

#embody

utilizing namespace std;

  

int countTriangles(int a[], int n)

  

    

    

    int cnt = zero;

  

    

    

    int pairs = zero;

  

    

    

    for (int i = n – 1; i >= zero; i–)

  

    

    

    cnt += (2 * pairs) / three;

    return cnt;

  

int predominant()

Striver(underscore)79 at Codechef and codeforces D

If you want GeeksforGeeks and want to contribute, you can too write an article utilizing contribute.geeksforgeeks.org or mail your article to [email protected] See your article showing on the GeeksforGeeks predominant web page and assist different Geeks.

Please Improve this text should you discover something incorrect by clicking on the “Improve Article” button under.

Article Tags :

thumb_up
Be the First to upvote.

Please write to us at [email protected] to report any subject with the above content material.

Post navigation

Previous

first_page Count of components whose absolute distinction with the sum of all the opposite components is bigger than okay

Share this put up!