Topcoder SRM 348, D2, 1000-point problem

Read over the problem (in http://community.topcoder.com/stat?c=problem_statement&pm=7753&rd=10672). As with a lot of these problems, the key is to reduce it to a graph problem that you know how to solve. In this case, consider each element of a to be a node in a directed graph, and let there be an edge from a[i] to a[j] if a[j] can directly follow a[i] in a maximum subsequence.

Now, what's the rule for that? There should be an edge from a[i] to a[j] if a[j] is greater than a[i] and there is no number between the two -- in other words there is no k such that i < k < j and a[i] < a[k] < a[j]. Here are graphs for each of their examples:

Example 0: {1, 3, 2, 6, 4, 5 }:

Example 1: {1000000000,100000000,10000000,1000000,100000,10000,1000,100,10,1}:

Example 2: {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}

Example 3: {564,234,34,4365,424,2234,306,21,934,592,195,2395,2396,29345,13295423,23945,2}

Now that you have this graph, what is a maximum subsequence? It's a path from a node with no incoming edges to a node with no outgoing edges. Given that, our job is to determine how many such paths there are. It should be easy to see that the number of paths is 4 in example zero, 10 in example 1, and 1 in example 2. What about example 3? That's a mess!

So, we can be quantitative. There is one path to any node with no incoming edges. Otherwise, the number of paths to a node is the sum of the number of paths to nodes incident to it. In example 1, there is one path to nodes one, three and two. There are two paths to node six and two paths to node four. And thus two paths to node five. So, the sum of paths to nodes with no outgoing edges is four.

How do we calculate this? Using topological sort! We start with nodes with no incoming edges. They have one path. Then we do a topological sort -- every time we process a node, we go through each of its edges, and add its number of paths to the nodes to which it is connected. Then we remove the edges. When we're done, we sum up the number of paths to nodes with no outgoing edges.

I'll put this calculation in all the examples below. I've colored nodes with no outgoing edges magenta. The sum of the values in these nodes is our answer:

Example 0: {1, 3, 2, 6, 4, 5 }:

Example 1: {1000000000,100000000,10000000,1000000,100000,10000,1000,100,10,1}:

Example 2: {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}

Example 3: {564,234,34,4365,424,2234,306,21,934,592,195,2395,2396,29345,13295423,23945,2}


Here are answers: SRM-348-D2-1000.cpp and SRM-348-D2-1000-main.cpp.