Sort the cows by their positions.
For each adjencent cows c(i) and c[i-1] (i is from 2 to n)do
calculate the distance d(i) between them
multiply d(i) with (i-1)*(n-i+1) is the contribution of this distance v(i)
The sum of all v(i) times 2 is the result.