8.15 老妹的难题 2700

来源:互联网 发布:python配置opencv3.0 编辑:程序博客网 时间:2024/06/05 04:25

  • 题目
  • 题解
  • 代码

题目

在洒落的礼物中找出一个,使之到其他礼物的距离之和最小。由于你老妹还没学开根号,所以我们定义(x1,y1)(x2,y2)两点间的距离为:|x2-x1|+|y2-y1|
你为了验证你老妹给出的答案是否正确,需要编写一个程序,来完成你老妹的任务。输出距离总和的最小值是多少。

30%的数据 N≤100
全部的数据N≤10^5
全部的数据 X i,Yi≤10000

题解

n^2的做法显然不行,那么可以考虑将问题转换一下:
规定两点间的距离为|x2-x1|+|y2-y1|,所以我们可以尝试把|x2-x1|和|y2-y1|分开考虑
排序加前缀和即可

                       小于a[i]的部分 ans[b[i]]:=ans[b[i]]+(i*a[i]-c[i])+(c[n]-c[i]-(n-i)*a[i]); 大于a[i]的部分

时间复杂度O(n)

代码

type  arr=array[0..100001]of longint;var  n,i,j,t,k:longint;  x,y,a,b,c,d,ans:arr;procedure qsort(l,r:longint);var  i,j,k,t:longint;begin  if l>=r then exit;  i:=l;j:=r;  k:=a[(l+r) div 2];  repeat    while a[i]<k do inc(i);    while a[j]>k do dec(j);    if i<=j then      begin        t:=a[i];a[i]:=a[j];a[j]:=t;        t:=b[i];b[i]:=b[j];b[j]:=t;        inc(i);dec(j);      end;  until i>j;  qsort(i,r);  qsort(l,j);end;begin  readln(n);  for i:=1 to n do    begin      readln(a[i],x[i]);      b[i]:=i;y[i]:=i;    end;  qsort(1,n);  for i:=1 to n do c[i]:=c[i-1]+a[i];  for i:=1 to n do ans[b[i]]:=ans[b[i]]+i*a[i]-c[i]+c[n]-c[i]-(n-i)*a[i];  a:=x;b:=y;  qsort(1,n);  for i:=1 to n do c[i]:=c[i-1]+a[i];  k:=maxlongint;  for i:=1 to n do ans[b[i]]:=ans[b[i]]+i*a[i]-c[i]+c[n]-c[i]-(n-i)*a[i];  for i:=1 to n do    if ans[i]<k then k:=ans[i];  writeln(k);end.