1

I'm solving one problem from past competitions in programming, so i need help, i will explain the problem in one sentence. You have an array with size of N, where N can go up to 10^5. And then in second line you have exactly N elements. So now you have to count the the ways to pick three elements from the array such that they will be in decreasing order. Here is example

N=4 and the array looks like this 190, 180, 170, 168. We have exactly four ways to pick those three elements. 1. (190, 180, 170) 2. (190,180,168) 3. (190, 170, 168) and 4. (180, 170, 168)

I think that this should be solved with segment tree but i don't know with which argument should i create the tree. Thanks in advance.

someone12321
  • 755
  • 5
  • 24
  • Are the elements unique? – rici Oct 19 '16 at 20:01
  • The most straightforward solution since you know you will have always pick three elements is to sort the array in descending order, and than iterate through it with three embedded loops, such as every next loop will start with previous index + 1. It will work only if elements are uniqe, and if you don't care about time of execution. – Kamil Banaszczyk Oct 19 '16 at 20:10
  • All elements are unique, and you cannot do brute force because N can go up to 10^5 and that will be (10^5)^3 which is too much – someone12321 Oct 20 '16 at 05:51
  • As I said in my answer below, C(n,3) does the trick. – hbejgel Oct 21 '16 at 17:23

1 Answers1

0
  1. We can assume that all numbers are in the [0, n - 1] range (otherwise, we can 'compress' them).

  2. Let's fix the position of the middle element in the triple. Now we can count the number of greater elements to the left from it and multiply by the number of smaller elements to the right from it.

  3. How to count the number of greater elements with smaller indices? Here is a pseudo code that explains it:

    tree = SegmentTree(0, n - 1) // for sum and add operations
    for i = 0 ... n - 1
        greaterLeft[i] = tree.getSum(a[i] + 1, n - 1)
        tree.update(a[i], 1)
    
  4. Note that we need updates in a point and a sum of a range. A binary index tree can do it efficiently (it is easier to implement than a segment tree).

kraskevich
  • 18,368
  • 4
  • 33
  • 45