SRM 309 DIV 2 hard

O(n^2) is always best in Topcoder..