Hints for SRM 486, D1, 450-Pointer (QuickSort)

James S. Plank

Wed Nov 20 16:15:31 EST 2013
Problem Statement.
This is a classic dynamic program. It shouldn't be too hard to spot the recursion:

double Quicksort::getEval(vector <int> L)
{
  v = 0;
  for (i = 0; i < k.size(); i++) {
    v += cost of making left partition with pivot i;
    v += cost of making right partition with pivot i;
    v += cost of sorting left partition with pivot i;
    v += cost of sorting right partition with pivot i;
  }
  v /= (double) k.size();
  return v;
}
Here's a trick that made my life a lot easier. Since the values of L are between 1 and 50, turn L into a string k whose characters are ('0'+L[i]). Then you can simply pass that string recursively to your sorting function. And you can use that string as a key to a map for memoization.

When you are creating the two partitions, simply have two strings l and r, which you create by calling push_back() when you run through the main string.


I'll help illustrate with an example. Let's use example 2. The string k, conveniently will equal "321". Here's what happens when you run through the "for" loop above:

Finally, divide 8 by 3, and you get the answer, 2.66666666....


For reference, in example 3, k will be "bXND:?IS]".