The code below is for: http://hihocoder.com/problemset/solution/237010 With enough comments to understand: