Editorial for COCI '11 Contest 2 #5 Funkcija
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:
The solution to our problem is the number of integer solutions of the given system of inequalities modulo .
Let's build a graph with nodes, each node representing one inequality. From a node which represents inequality of we'll put an edge towards node of if upper or lower bound of is equal to the same-kind bound of .
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 be equal to the number of solutions of the tree rooted at . Let be equal to the number of solutions of a subtree rooted at , if variable bound for that node inequality is equal to . We'll now make the following claims:
for inequality with variable lower bound (it is analog in the case of variable upper bound). This algorithm has a complexity of , where is a limit on the upper bound, which is good enough for 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):
Using this observation, complexity becomes and this wins points.
Comments