Codechef Not a Triangle

Source: Internet
Author: User

Find the three numbers in an array. The three numbers cannot form triangles.

The condition that the three numbers cannot form a triangle is: a + B <c

And smaller than the third side.

This problem is a combination of three numbers. The violence law can be solved, but the time efficiency is O (n * n), which is very slow.

However, since it is a combination problem, the post-sorting method can be used to reduce the time efficiency.


The method to reduce the time efficiency is as follows:

Select a maximum number c, and then select two decimals a and B, where a <B. if the conditions are met, then, the numbers in the two numbers must be used as B to meet the condition a + B <c

In this way, the time efficiency can be reduced to O (n * n ).


This rule is hard to find. Take a very careful look and summarize it.

To process an array, We need to observe the rule from small to large, from large to small.


Original question: http://www.codechef.com/problems/NOTATRI/


# Include
 
  
# Include
  
   
# Include using std: sort; class NotATriangle {// carefully find out the rule to optimize int getNotTris_3 (int * A, const int n) {sort (A, A + n ); int I = 0, j = 1, k = n-1, ans = 0; for (; k> = 2; k --) {I = 0, j = K-1; while (I <j) {if (A [I] + A [j] <A [k]) {ans + = j-I; I ++ ;} else j -- ;}} return ans;} public: NotATriangle () {int N = 0; while (scanf ("% d", & N) & 0! = N) {int * A = (int *) malloc (sizeof (int) * N); for (int I = 0; I <N; I ++) {scanf ("% d", & A [I]);} printf ("% d \ n", getNotTris_3 (A, N )); free (A) ;}}; int notATriangle () {NotATriangle ntio; return 0 ;}
  
 



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.