Editorial for COCI '11 Contest 2 #5 Funkcija


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

The first observation we can make is that loops actually represent a system of inequalities:

\displaystyle \begin{array}{c}
X_1 \le a \le Y_1 \\
X_2 \le b \le Y_2 \\
\vdots \\
X_N \le \langle N^\text{th} \rangle \le Y_N
\end{array}

The solution to our problem is the number of integer solutions of the given system of inequalities modulo 1\,000\,000\,007.

Let's build a graph with N nodes, each node representing one inequality. From a node which represents inequality of var1 we'll put an edge towards node of var2 if upper or lower bound of var2 is equal to the same-kind bound of var1.

This graph is a disjunct union of directed rooted trees. Since variables in different trees are independent of each other, the number of solutions for the inequality system is equal to the product of number of solutions for each of the trees. Let us demonstrate how to calculate the solution for only one tree.

Let f(root) be equal to the number of solutions of the tree rooted at root. Let g(node, number) be equal to the number of solutions of a subtree rooted at node, if variable bound for that node inequality is equal to number. We'll now make the following claims:

\displaystyle \begin{align*}
f(root) &= \sum_{i = X(root)}^{Y(root)} \prod_{child \in children(root)} g(child, i) \\
g(node, number) &= \sum_{i = number}^{Y(number)} \prod_{child \in children(node)} g(child, i)
\end{align*}

for inequality with variable lower bound (it is analog in the case of variable upper bound). This algorithm has a complexity of \mathcal O(NM^2), where M is a limit on the upper bound, which is good enough for 70\% of the points. Further, we can notice that the following holds (for the variable lower bound case - as before it is analog with variable upper bound):

\displaystyle g(node, number) = g(node, number+1) + \sum_{child \in children(node)} g(child, number)

Using this observation, complexity becomes \mathcal O(NM) and this wins 100\% points.


Comments

There are no comments at the moment.