I and OI
Past...

题意:给出N个数,求形成的N^2对数的差的绝对值之和.(N<=10000)

分析:N^2做肯定不行.我们看ai这个数与其他数对答案的贡献.

sum=∑|ai-aj|.去掉绝对值,如果有k个数比ai小,那么ai为sum贡献了k个+ai,

n-k-1个-ai.然后算法就清晰了,排序,O(N)地扫一遍统计答案.

code:

var   a:array[0..10001] of longint;
      n,i,j:longint;
      ans,now:int64;

      procedure sort(l,r:longint);
      var   i,j,mid,temp:longint;
      begin
            i:=l; j:=r;
            mid:=a[(l+r)>>1];
            repeat
                   while a[i]<mid do inc(i);
                   while a[j]>mid do dec(j);
                   if i<=j then
                   begin
                         temp:=a[i];
                         a[i]:=a[j];
                         a[j]:=temp;
                         inc(i); dec(j);
                   end;
            until i>j;
            if i<r then sort(i,r);
            if j>l then sort(l,j);
      end;

begin
      readln(n);
      for i:=1 to n do readln(a[i]);
      sort(1,n);

      for i:=1 to n do
         inc(ans,int64(a[i])*int64(i-1)-int64(a[i])*int64(n-i));

      writeln(ans*2);
end.
posted on 2011-08-12 16:26  exponent  阅读(511)  评论(0编辑  收藏  举报