https://codeforces.com/problemset/problem/613/D + Editorial
https://discuss.codechef.com/t/icl1705-editorial/14269