CQOI2011分金币&HAOI2008糖果传递

双倍经验……

没想到白书上竟然有……我还看过……还忘了……

抄份题解:

A1 + X1 - X2 = G

A2 + X2 - X3 = G

.

.

.

An + Xn - X1 = G

解得

X1 = X1

X2 = A1 - G + X1

X3 = A1 + A2 - G - G + X1

.

.

.

Xn = sigma(1, n)A - n * G + X1

注意到ans = abs (X1 - lamda1) + abs (X2 - lamda2) + ... + abs (Xn - lamdan)

于是sort 取中位数

 代码:

 1 var i,n:longint;
 2     x1,tot,ave,ans:int64;
 3     a,c:array[0..1500000] of longint;
 4 procedure sort(h,l:longint);
 5  var i,j,m,temp:longint;
 6  begin
 7    i:=h;j:=l;m:=c[(i+j)>>1];
 8    repeat
 9      while (c[i]<m) do inc(i);
10      while (c[j]>m) do dec(j);
11      if i<=j then
12       begin
13         temp:=c[i];c[i]:=c[j];c[j]:=temp;
14         inc(i);dec(j);
15       end;
16    until i>j ;
17    if i<l then sort(i,l);
18    if j>h then sort(h,j);
19  end;
20 procedure main;
21  begin
22   readln(n);
23   tot:=0;
24   for i:=1 to n do
25    begin
26      readln(a[i]);inc(tot,a[i]);
27    end;
28   ave:=tot div n;
29   c[0]:=0;
30   for i:=1 to n-1 do c[i]:=c[i-1]+a[i]-ave;
31   sort(0,n-1);
32   ans:=0;x1:=c[n>>1];
33   for i:=0 to n-1 do inc(ans,abs(x1-c[i]));
34   writeln(ans);
35  end;
36 begin
37  main;
38 end.       
View Code

 

posted @ 2014-06-21 13:15  ZYF-ZYF  Views(277)  Comments(0Edit  收藏  举报