Circular Barn (Silver)

Cows waiting at ring doors walk clockwise to fill each room with one cow at the smallest total squared walking distance.

Medium5Dynamic programmingBrute forceInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

Farmer John has built a new barn shaped as a perfect circle. Inside, nn rooms form a ring, numbered 11 through nn clockwise around the perimeter of the barn (3n10003 \le n \le 1000). Each room has a door to each of its two neighboring rooms, and one more door that opens to the outside of the barn.

Farmer John owns nn cows and wants exactly one cow to end up in each room. The cows line up at arbitrary outside doors, and several of them may pick the same door. Exactly cic_i cows line up outside the door of room ii, and ci=n\sum c_i = n. Every cic_i is a nonnegative integer.

To get one cow into each room, Farmer John uses this procedure. Each cow enters through the door where she lined up, then walks clockwise from room to room until she reaches the room she is assigned to. A cow that walks through dd doors spends d2d^2 energy. Find the smallest total energy the cows can spend while filling every room with exactly one cow.

Input

The first line contains nn. Each of the next nn lines contains one value, c1c_1 through cnc_n in order.

Output

Print the smallest total energy the cows spend.