我可以考虑更快的解决办法。 如果我不错,就去O(n*logn)。 现在,根据Pi,首先让所有城市,即O(n* 标志n)。 然后,我们开始处理这些城市,以便增加Pi的顺序,原因是,你总是知道,在这种情况下,Pi(Pj) = Pi。 我们只想增加与Pi关系中的所有部分,这些部分将与较大指数挂钩,将在处理时计算。
Now the thing I was able to think of was to use several index trees in order to reduce the complexity of the algorithm. First index tree is counting the number of nodes and can process queries of the kind: how many nodes are to the right of xi in logarithmic time. Lets call this number NR. The second index tree can process queries of the kind: what is the sum of distances from all the points to the right of a given x. The distances are counted towards a fixed point that is guaranteed to be to the right of the rightmost point, lets call its x XR.Lets call this number SUMD. Then the sum of the distances to all points to the right of our point can be found that way: NR * dist(Xi, XR) - SUMD. Then all these contribute (NR * dist(Xi, XR) - SUMD) *Pi to the result. The same for the left points and you get the answer. After you process the ith point you add it to the index trees and can go on.
Edit: Here is one article about Biary index trees: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees