孤独一生

来源:互联网 发布:cg网络语是啥意思 编辑:程序博客网 时间:2024/04/29 17:11

题目描述 下课了,Polo来到球场,但他到了之后才发现…..被放了飞机……

无事可做的他决心找点乐子,比方说……跳台阶……

球场边有N个台阶拍成一行,第i个台阶的高度是Hi(Hi<=10^9),第0个台阶,也就是地面的高度为0。Polo打算把这N个台阶分成两个集合Sa,Sb(可以为空),对于一个台阶集合S={P1,P2,…P|S|}(pi从小到大)

sigma{|S| i=1} {Hpi-Hpi-1}

的体力值来完成。

现在他希望两次跳跃所需的总体力值最小,你能帮帮他吗?

输入 第一行一个数N。

第二行N个整数Hi。

输出 一行一个整数,表示最小的总体力值。

样例输入
3
1
3
1
样例输出
4
提示
对于10%的数据N<=20。

对于20%的数据N<=100。

对于50%的数据N<=5000。

对于100%的数据1<=N<=500000。

设计dp方程,记f[i,j]表示一个集合结尾到i,另一个结尾到j所需的最小体力值。
当i>j-1 时 f[i,j]=f[i-1,j]+abs(h[i]-h[i-1])
当i=j-1 时 f[i,j]=min(f[j,k]+abs(h[i]-h[k]));

我们发现只有当j=i-1时需要从前面的状态转移。于是我们记g[i]表示f[i,i-1]。预处理前缀和sum[i]=sum[i-1]+abs(h[i]-h[i-1]);
g[i]=min(g[j]+sum[i-1]-sum[j]+abs(h[i]-h[j-1]);

上述方程已经很节俭了,但是我们得用数据结构来优化,具体来说就是用数据结构记录g[j]-sum[j]+h[i]和g[j]-sum[j]-h[i]的最小值,这样转移时间复杂度就变成了O(logN)了。

varn,i,j,pre,num:longint;ans,s1,s2:int64;h,g,sum,tmin1,tmin2,a,hash,p:array[0..500055] of int64;function min(a,b:int64):int64;begin  if a<b then exit(a) else exit(b);end;procedure sort(l,r:longint);vari,j,t,m:longint;begin  i:=l;j:=r;m:=a[(i+j) div 2];  repeat    while a[i]<m do inc(i);    while a[j]>m do dec(j);    if i<=j then    begin      t:=a[i];a[i]:=a[j];a[j]:=t;      t:=p[i];p[i]:=p[j];p[j]:=t;      inc(i);dec(j);    end;  until i>j;  if i<r then sort(i,r);  if j>l then sort(l,j);end;function lowbit(x:longint):longint;begin  exit(x and -x);end;function ask1(x:longint):int64;varans:int64;begin  ans:=10000000000000000;  while x>0 do  begin    ans:=min(ans,tmin1[x]);    x:=x-lowbit(x);  end;  exit(ans);end;function ask2(x:longint):int64;varans:int64;begin  ans:=10000000000000000;  while x>0 do  begin    ans:=min(ans,tmin2[x]);    x:=x-lowbit(x);  end;  exit(ans);end;procedure change1(x:longint;y:int64);begin  while x<=num do  begin    tmin1[x]:=min(tmin1[x],y);    x:=x+lowbit(x);  end;end;procedure change2(x:longint;y:int64);begin  while x<=num do  begin    tmin2[x]:=min(tmin2[x],y);    x:=x+lowbit(x);  end;end;begin  readln(n);  for i:=1 to 500005 do  begin    tmin1[i]:=100000000000000;    tmin2[i]:=100000000000000;  end;  for i:=1 to n do  begin    read(h[i]);    a[i]:=h[i];    p[i]:=i;    sum[i]:=sum[i-1]+abs(h[i]-h[i-1]);  end;  sort(1,n);  num:=1;  for i:=1 to n do  begin    if a[i]<>pre then    begin      num:=num+1;      pre:=a[i];    end;    hash[p[i]]:=num;  end;  g[1]:=h[1];  change1(1,0);  change2(num,0);  ans:=10000000000000;  for i:=2 to n do  begin    s1:=ask1(hash[i]);    s2:=ask2(num-hash[i]+1);    s1:=s1+h[i];    s2:=s2-h[i];    g[i]:=min(s1,s2)+sum[i-1];    change1(hash[i-1],g[i]-sum[i]-h[i-1]);    change2(num-hash[i-1]+1,g[i]-sum[i]+h[i-1]);    ans:=min(ans,sum[n]-sum[i]+g[i]);  end;  write(ans);end.
0 0
原创粉丝点击