finding triangulars from array

后端 未结 5 782
一向
一向 2021-01-07 12:58

zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if and

A[P] + A[Q] > A[R], 
A[Q] + A[R] > A[P], 
A[R] + A[P         


        
5条回答
  •  甜味超标
    2021-01-07 13:39

    First claim

    First of all there is no point to take into account non-positive number. There's no chance you may achieve the triangle inequalities if at least one of the numbers is negative or zero. This is obvious, nevertheless here is the proof:

    Assume A, B, C obey the triangle inequality, whereas C <= 0. Then you have

    • A + C > B. Hence A > B.
    • B + C > A. Hence B > A.

    (contradiction).

    Second claim

    Suppose A, B, C obey the triangle inequalities, whereas C is the largest among A,B,C. Then for each A2 and B2 between A,B respectively and C - they will also obey triangle inequality.

    In other words:

    • A,B,C obey triangle inequalities.
    • C >= A
    • C >= B
    • C >= A2 >= A
    • C >= B2 >= B
    • Then A2,B2,C also obey triangle inequalities.

    The proof is trivial, enough to write the inequalities explicitly.

    The consequence of this is that if C is the largest number for which you want to find the triangle inequality - you should check only two largest numbers from the set not exceeding C, and check if A + B > C.

    Third claim

    If 0 < A <= B <= C don't obey triangle inequalities, then C >= A*2.

    The proof is trivial as well: A + B <= C, hence A + A <= C, hence C >= A*2

    The algorithm

    1. Pick 2 largest numbers B and C (B <= C).
    2. Pick the largest number A not exceeding B, such that
      • A <= B <= C.
      • Make sure it's not the same element as B,C
      • Take into account only positive integers.
      • If unable to pick such a number - done. (No triangulars).
    3. Check if A,B,C obey the triangle inequality. Test if A + B > C. (done if they do).
    4. Discard the largest number C. Substitute C = B, then B = A.
    5. Go to step 2.

    Fourth claim

    The above algorithm is logarithmic in the maximum integer size. In other words, its linear in the data type bitness. It's worst-case complexity is independent on the input length. Hence - it's O(1) in the input length.

    Proof:

    At every iteration (that does not find the solution) we have A <= C/2. After two such iterations A becomes the new C. This means that after every two iterations the largest number becomes at least 2 times smaller.

    Obviously this gives us the upper bound of the number of the iterations. Gives our integers are limited by 31 bit (we ignore negatives), whereas the minimum interesting largest C is 1, this gives us no more that 2 * (31 - 1) = 60 iterations.

提交回复
热议问题