Unable to solve this problem.

Please help me in solving this problem. http://www.spoj.com/problems/FP
This is a typical dp problem , but my solution is getting TLE. I am unable to optimize it further. Please help me in solving this problem.
My solution : http://ideone.com/faMyky