http://codeforces.com/contest/427/problem/C
Here is the link to my solution:
http://codeforces.com/contest/427/submission/11352911
It's just implemented as said in the editorial, but somehow it fails on test case 71. I've checked for any overflow problems or other bugs, but it gives WA.