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:
- i=0, k[i] = '3':
- The left partition is "21".
- The right partition is "".
- The cost of making the left partition is 2.
- The cost of making the right partition is 0.
- Call your procedure recursively on "21" (it will return 1), and "" (it will return 0).
- Therefore, at this point, v = 3.
- i=1, k[i] = '2':
- The left partition is "1".
- The right partition is "3".
- The cost of making the left partition is 1.
- The cost of making the right partition is 1.
- Call your procedure recursively on "1" (it will return 0), and "2" (it will return 0).
- Therefore, at this point, v = 5.
- i=2, k[i] = '1':
- The left partition is "".
- The right partition is "32".
- The cost of making the left partition is 0.
- The cost of making the right partition is 2.
- Call your procedure recursively on "" (it will return 0), and "32" (it will return 1).
- Therefore, at this point, v = 8.
Finally, divide 8 by 3, and you get the answer, 2.66666666....
For reference, in example 3, k will be "bXND:?IS]".