# FIBTREE - Editorial

**Problem link** : [contest][1] [practice][2]
**Difficulty** : Hard
**Pre-requisites** : heavy-light decomposition, segment trees, persistence
**Solution** :
First, let's recall one of the properties of Fibonacci numbers: the **n**-th Fibbonacci number is **ax<sup>n</sup>+(1-a)y<sup>n</sup>**, where:
- **a** equals to **(3+sqrt(5))/(5+sqrt(5))**;
- **x** equals to **(1+sqrt(5))/2**;
- **y** equals to **(1-sqrt(5))/2**.
So, the sum of the first **K** Fibbonacci numbers is basically the sum of two progressions.
Now there are still two questions:
1. How do we operate with floating point numbers? How do we avoid the precision loss?
2. How do we add the geometric progression on a segment?
The answer to the first quesion is: we don't operate with floating point numbers/doubles at all. This can be achieved this way: since our modulo **1000000009** is a prime, we can find such integer **T** that its' square modulo **1000000009** is **5**. This way we can define **sqrt(5)** in the modulo ring. Now we have that **sqrt(5)** is an integer, so all the operations become ordinary modular arithmetic operations.
Now we can have a segment tree for the progressions addition. [Here][3] is the tutorial on developing such kind of segment trees.
When we have a segment tree, it's time to make in persistent and to build the heavy-light decomposition of the tree. Pay attention that if you store all the chains of the HLD in the single segment tree, there is no more effort required to maintain the versions of the persistence correctly. But if not, you'll also have to store some persistent array to get access to the right version of some exact chain. [Here][4] is the detailed desription of persistent heavy-light decomposition's implementation.
Setter's solution: [link][5]
Tester's solution: [link][6]
[1]: http://www.codechef.com/SEPT14/problems/FIBTREE/
[2]: http://www.codechef.com/problems/FIBTREE/
[3]: http://discuss.codechef.com/questions/42557/funagp-editorial
[4]: http://discuss.codechef.com/questions/6548/query-editorial
[5]: http://www.codechef.com/download/Solutions/2014/September/Setter/FIBTREE.cpp
[6]: http://www.codechef.com/download/Solutions/2014/September/Tester/FIBTREE.cpp