Showing posts with label sorting. Show all posts
Showing posts with label sorting. Show all posts

Friday, 26 October 2012

All Possible Increasing Subsequences

Problem Name: All Possible Increasing Subsequences
LightOJ ID: 1085
Keywords: sorting, binary indexed tree

Continuing with my plan to write about data structures I have recently discovered, I’ll talk about a problem that can be solved with the help of a binary indexed tree. But we’ll get to that in a moment; let’s focus on the problem first.

In this problem we’re asked to consider sequences of integers. An increasing subsequence is simply an arbitrary subset of integers from the original sequence, kept in the same relative order, such that the numbers in the subsequence are in strictly ascending order. Putting it into more formal terms, let \(A\) be an array of \(N\) integers (indexed from zero to \(N-1\)). Then an increasing subsequence of length \(k\) can be described by a list of indices \(s_1, s_2, \ldots, s_k\) such that \(0 \leq s_1 < s_2 < \ldots < s_k < N\) and \(A[s_1] < A[s_2] < \ldots < A[s_k]\). Note that a subsequence can be of length one, which means that any number in \(A\) by itself forms an increasing subsequence.

The problem consists of finding the total number of increasing subsequences that can be found in a given sequence of integers. Let’s get our hands dirty with a simple example, which is always helpful to wrap our heads around problems and their solutions.

Here we have an array \(A\) of 10 elements, all distinct integers (pretty integers, by the way). At this point, you can try to find out the number of increasing subsequences in \(A\) by yourself, if you feel inclined to do so.

If you haven’t figured out a way to solve it yet, I recommend you give it a try, at least for a few minutes. It is important to spend the time doing that mental workout. Here’s a little hint, before I blurt out the strategy I have in mind: think about going step by step, in order.

Okay, here’s how the process might look like for this example. Hopefully it will help you get a grip on the core of the algorithm we’re going to use. We’ll take elements from the original sequence, one by one and in ascending order, and find out the number of increasing subsequences (ISS) we have found so far at each step:

A few steps have been left out (try to complete the list), but did you get the gist of it? Let’s put it into words:

  • Let \(S\) be an array of length \(N\), where \(S[i]\) will represent the number of increasing subsequences that end at position \(i\) (so the last number of those subsequences would be \(A[i]\)). Initially, all positions inside \(S\) will be set to zero.
  • Consider tuples of the form \((A[i], i)\) for all \(0 \leq i < N\). Create all these tuples and sort them by their first element.
  • Take each tuple \((A[i], i)\) in order, and perform the following calculation: \(S[i] = 1 + \sum_{j=0}^{i - 1}{S[j]}\)

With this, we have successfully calculated the number of ISS that end on each position of the array. The final answer is simply the sum of all elements from \(S\).

You might be thinking, all of this is very nice except for one small detail: the array \(A\) can be very large (its size can be up to \(10^5\)), and calculating all those sums make up for a complexity of \(O(N^2)\), which is prohibitively high!

That’s where our new data structure comes out to save the day. A binary indexed tree —also called a Fenwick tree— is a data structure that can store and update cumulative sums (prefix sums) in logarithmic time, as opposed to the traditional \(O(n)\) from a naive loop to accomplish the same task in an array. The way BITs work is fascinating, in case you want to delve into it a little more, but what’s important in the context of this problem is that by using a BIT, we can calculate all those sums in our algorithm very efficiently. So our problems disappear if we simply choose to implement \(S\) as a BIT (some adjustments are necessary, though, because BITs are not zero–indexed).

There is only one additional detail we haven’t considered yet. What happens if there are repeated numbers in \(A\)? Try it with pen and paper. Create a small array with some numbers occurring more than once. Now try to apply the algorithm described here. Can you identify the exact adjustment that needs to be done? Here’s a hint: it’s related to the sorting of the tuples. They need to be sorted by their first element first, but if there’s more than one tuple with the same first element, then the comparison needs to be done by their second element. But how? I’ll leave it as an exercise… Have fun :).

Friday, 13 July 2012

Bubbles and Buckets

Problem Name: Bubbles and Buckets
UVa ID: 11495
Keywords: sorting, inversion number

Since my previous post was about a problem that can be solved with a variation of a classic sorting algorithm, I thought it would be nice to do a follow–up with another problem that can also be solved by using a sorting algorithm as a basis.

In this problem it is said that two boys play a simple game: a random permutation of the first \(N\) positive integers is given, and then the two players take turns to make a move. A valid move consists of taking any pair of adjacent numbers that are in the wrong order (the first number is higher than the second), and swapping them. The player who can’t make a move (which means the list is completely sorted) loses. The question is, knowing the initial permutation, and the player who goes first, who wins?

Clearly, the core of this problem is finding the number of swaps between adjacent elements required to sort the list. If you don’t know how to find this value yet, take some time to look at the samples, and think about possible strategies to do it. You should be able to identify a few interesting invariants soon. For example: an indication of how far a number \(x_i\) is from its correct position is the amount of numbers larger than \(x_i\) that are located to its left, or the amount of numbers smaller than \(x_i\) that are located to its right. Let’s consider the first test case from the sample input:

In the table, \(\alpha\) represents the amount of numbers bigger than \(x_i\) that are left of the given number, and \(\beta\) is the amount of numbers smaller than \(x_i\) that are found to its right. As you can see, the sums from the \(\alpha\) and \(\beta\) rows are equal. That’s an invariant, and it’s related to the algorithm that we will ultimately use to calculate the answer.

Another way to look at it is this: \(\alpha\) and \(\beta\) are the amount of swaps that every number has to go through to sort the list. \(\alpha\) corresponds to swaps from right to left, and \(\beta\) to swaps from left to right. No matter the orientation of the swaps you choose, the total number of swaps will always be the same. In discrete mathematics, this is also known as the inversion number of a sequence.

Now, how to calculate this efficiently? Note that there can be up to \(10^5\) numbers in the list, so any kind of \(O(n^2)\) algorithm wouldn’t work. Well, we can just choose any of the \(O(n \log{n})\) sorting algorithms and adapt it to keep track of the number of times a swap in one particular direction has to be performed. One particularly good alternative is merge sort because of its simplicity, in contrast to something like quick sort, where —depending on your implementation and the way you handle the pivot— figuring out the number of swaps required when a number has to change its place can be significantly harder.

Having settled on the algorithm to use, let’s see an example of the implementation of merge sort for this problem:

typedef long long    i64;
typedef vector<int>  IV;
typedef IV::iterator IVi;

i64 n_swaps;  // the number of swaps can be very large

// auxiliary function used by merge_sort
void merge(IVi lo, IVi hi, IVi mid)
{
    IV x;
    for (IVi a = lo, b = mid; a < mid || b < hi; ) {
        if (a >= mid) { x.push_back(*b++); continue; }
        if (b >= hi) { x.push_back(*a++); continue; }
        if (*a < *b) { x.push_back(*a++); continue; }

        x.push_back(*b++);

        // here is the problem-specific adjustment
        // what does (mid - a) correspond to?
        n_swaps += mid - a;
    }
    for (IVi a = lo, b = x.begin(); a < hi; ++a, ++b)
        *a = *b;
}

// merge sort algorithm, receives iterators to the first (inclusive)
// and last (exclusive) elements of the range to sort
void merge_sort(IVi lo, IVi hi)
{
    if (hi <= lo + 1) return;
    IVi mid = lo + ((hi - lo) / 2);
    merge_sort(lo, mid);
    merge_sort(mid, hi);
    merge(lo, hi, mid);
}

For a similar problem —the algorithm is exactly the same, the main difference is that you have to print the number of swaps— see the problem Ultra-QuickSort (UVa ID 10810). Another similar problem, but with lower constraints (enough to make a \(O(n^2)\) solution feasible) is Flip Sort (UVa ID 10327).

Tuesday, 10 July 2012

Aladdin and the Optimal Invitation

Problem Name: Aladdin and the Optimal Invitation
LightOJ ID: 1349
Keywords: math, median, sorting, recursion, quickselect

Sometimes you come across a problem that forces you to look into new, interesting algorithms, which is always an excellent opportunity to extend your bag of tricks as a programmer, and can give you a new level of understanding of classic algorithms you take for granted. This problem is a good example.

You are given a rectangular matrix of integers, representing a town, where the integer values of each cell represent the amount of people living on that cell. You are asked for a particular position inside the matrix, such that the total sum of Manhattan distances of all people relative to that position is minimised. One thing you can quickly notice is that in this 2D problem you can consider each axis independently and combine the horizontal and vertical cases for your final answer.

Now, let’s think abstractly about the problem in one dimension; that is, given a set of 1-dimensional coordinates, find an optimal coordinate such that the total sum of distances from each point of the set to that optimal position is minimal. If you have come across this type of problem before, you probably know already that the answer is the median of the set of points. In case it’s not clear why, let’s stop for a moment and try to find a satisfying explanation:

~~~ math intermission ~~~

Let’s express the total sum of distances of all the points in the set to an arbitrary position \(x\) as a function:

Where \(p_i\) is each point from the set, and \(n\) is the number of points. Now, doing some mathematical optimisation, we find the first derivative of \(f\):

Where \(A\) is the number of points above \(x\), and \(B\) is the number of points below \(x\). The function \(f\) is minimal when its first derivative equals zero, which happens when the amount of points above \(x\) is the same amount of points below \(x\), or, in other words, when \(x\) is the median of the set of points. Note that there could be more than one value of \(x\) that satisfies the relation, which is consistent with the fact that the median is ambiguous when the number of points is an even number.

~~~ end of intermission ~~~

Solving this type of problem for relatively small data samples is very straightforward, just store the points in a list, sort the list, and find the value in the middle. For an example of a programming problem that can be solved this way, see Vito’s Family (UVa ID 10041). However, the constraints in this problem make it impossible to solve it with that approach. There can be \(5 \times 10^4\) populated cells in the matrix, and a maximum of \(10^4\) people can live on each cell.

One way to solve this is using an algorithm known as “quick select”. A good explanation on this algorithm can be found here: Selection and order statistics. You don’t have to read the whole article, but at least make sure to glance over the “Quick select” and “Analysis of quickselect” sections.

You can think about it as a variation of the standard quick sort algorithm. In quick sort you receive a list of values, choose one of them as a pivot and then partition the list into three groups: the values to the “left” of the pivot, the values to the “right” of the pivot, and the pivot itself. If any of the left of right groups is not empty, you then call quick sort recursively on them. Quick select is very similar, but the difference is that its purpose is not sorting the list, but finding an arbitrary element in the list (let’s call it the \(k\)th position).

So the algorithm chooses a pivot (just like quicksort), partitions the list, but then it simply does the following checks:

  • If the left group has at least \(k\) elements, then the \(k\)th element must be found there, so call quickselect recursively on that group.
  • If the pivot is exactly the \(k\)th element, then the pivot has to be returned.
  • Otherwise, the answer must be found on the right group, so make the recursive call on that.

In a way, this algorithm is simpler than quick sort because it doesn’t need to make recursive calls for the groups where it knows that the \(k\)th element is not going to be found. With all of this in mind, now let’s see a C++ implementation of quick select specifically tailored for this problem, heavily based on the pseudo-code for the “in-place” version of quick sort from Wikipedia.

struct Data {
    int v;  // value of data point (one-dimensional coordinate)
    int n;  // number of occurrences (people on that coordinate)
    int p;  // a sequential number, to break ties

    Data(int V, int N, int P) : v(V), n(N), p(P) {}

    bool operator<(const Data &x) const {
        if (v != x.v) return v < x.v;
        if (n != x.n) return n < x.n;
        return p < x.p;
    }
};

// we will use STL's vector
typedef vector<Data> DV;
typedef DV::iterator DVi;

/**
 * Selects an arbitrary position from a range of data, according
 * to its logical order. It modifies the vector in-place.
 *
 * @param lo The iterator to the first element in the range (inclusive)
 * @param hi The iterator to the last element (exclusive)
 * @param k  Index of the element to return (starting with 0)
 *
 * @return The kth element in order from the range of data
 */
int select_kth(DVi lo, DVi hi, int k)
{
    // if there is only one element left, it must be the answer
    if (hi == lo + 1) return lo->v;

    // choose a pivot at random
    int pivot_index = rand() % (hi - lo);

    // move the pivot to the last position
    swap(*(lo + pivot_index), *(hi - 1));

    // keep the pivot's value at hand
    Data piv = *(hi - 1);

    // iterator to keep track of the "left" group
    DVi x = lo;

    // number of people that has gone to the "left" group
    int lt = 0;

    // traverse the range of data
    for (DVi i = lo; i < hi - 1; ++i)
        if (*i < piv) {
            // if the current element belongs to the left group ..

            swap(*i, *x);  // move it to the tail pointed by x
            lt += x->n;    // increase the number of people
            ++x;           // move the x iterator
        }

    // move the pivot back to its rightful place
    swap(*x, *(hi - 1));

    // if k is found in the left group
    if (k < lt)
        return select_kth(lo, x, k);

    // if k is greater than the amount of people in the left group
    // and the pivot
    if (k >= lt + x->n)
        return select_kth(x + 1, hi, k - lt - x->n);

    // the only possibility now is that k is in the pivot
    return x->v;
}

As you can see, it follows the quick sort pattern very closely, but it doesn’t bother sorting the entire list, just locates the \(k\)th element.

A couple of details are worth noting: the use of an extra field (p) in the Data structure (line 4), and the selection of the pivot at random (line 35). Both are related to the same issue: performance. If you read the comments on the performance of this algorithm in the article cited above, you realise that it can have a \(O(n^2)\) complexity for a worst case, but it is asymptotically optimal if the pivots are chosen carefully.

I actually came across this issue while testing my solution. Consider a test case with \(q=50000\), where \(u\) and \(v\) are always the same, and \(w\) is always \(10000\). If we always choose the pivot to be, let’s say the first element of the range, then it’s clear that on each call of the select_kth function the “left” group will be empty, and it will keep calling itself after discarding only one element from the list (the pivot). Clearly in this case it will perform very badly.

However, by always choosing the pivot randomly, and by making sure that the Data points can always be sorted unambiguously, the “left” groups will be of an average size, and the total complexity gets reduced drastically.


I really liked how this problem shows that, even if you would very rarely need to write a quick sort function (using the implementation from your programming language is a much better idea), knowing its inner workings is very useful to implement variations like quick select, which has the potential to provide elegant solutions in problems related to selecting elements from large lists.