The main idea: Farmer John again disgusting us! This time he brought some cows, these steaks into a column, their position given, each cow has a tone. Each of these cows communicates with each of the two cows, but there will be some cost when communicating, i,j two bulls = max (vi,vj) * |posi-posj|. The cost of exchange between all cows.
Thinking: At first I thought it was the biggest or the smallest cost, and then carefully read the question found to think more, is simple statistics, but the data range 2w obviously can not n^2 statistics, we need to think of some optimization methods.
For all bulls, the final calculation cost is determined by the high-pitched bull. So consider whether you can sort the tones from low to high, and then keep adding cows to them. So every time the cows add in, the previous cow's tone is lower than the added, it can be added in the new cattle to calculate.
Notice that every newly added cow needs to add ΣVX * |posx-posi| so much to ans that VX already knows, so how do you find the sum of the distances? My approach is to maintain 4 tree arrays, counting the sum of the distance from all points in front of X to the origin, how many cows are in front of X, and the sum of the distance from the point to the origin of the points behind X, and how many cows are behind X. This allows you to calculate the sum of the distance x in front of x by CNT * POSX-σpos_pred, and the same goes for the back.
Analysis of time complexity, O (NLOGN), water over bar.
CODE:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAX 200010using namespace Std;struct complex{int Val,pos;bool operator < (const Complex &a) Const {return Val < a.val; }void Read () {scanf ("%d%d", &val,&pos);}} Point[max];int Points;long long Pred[max],cnt1[max];long long succ[max],cnt2[max];inline void FixPred (int x); inline void fixsucc (int x), inline long long getpred (int x), inline long long getsucc (int x), int main () {cin >> points;for (int i = 1;i <= points; ++i) Point[i]. Read (); Sort (point + 1,point + points + 1); long long ans = 0;for (int i = 1;i <= points; ++i) {ans + = getpred (point[i].po s) * Point[i].val;ans + = GETSUCC (point[i].pos) * POINT[I].VAL; Fixpred (Point[i].pos); FIXSUCC (Point[i].pos);} cout << ans << endl;return 0;} inline void fixpred (int x) {for (int i = X;i < Max;i + = I&-i) {Pred[i] + = X;++cnt1[i];}} inline void fixsucc (int x) {for (int i = X;i;i = I&-i) {Succ[i] + = X;++cnt2[i];}}inline Long Long getpred (int x) {Long long re = 0,cnt = 0;for (int i = X;i;i = i&-i) Re + = pred[i],cnt + = Cnt1[i];retu RN cnt * X-RE;} Inline long long getsucc (int x) {Long long re = 0,cnt = 0;for (int i = X;i < Max;i + = i&-i) Re + = succ[i],cnt + = cnt2[ I];return re-cnt * x;}
POJ 1990 Moofest Tree-like array