SRM 317 DIV 2 hard

DP is awesome!