How to solve ADADIG on spoj

problem: LINK

//