标签:des style c class blog code
这是04年NOIP普及组的一道题,题目如下:
分析:
刚开始拿到此题,心里一阵窃喜,这不就是最优二叉树的问题么?于是照着哈夫曼树的代码敲了一下,结果发现只有50分,后面的5个数据全部超时.
代码如下:
const maxn=10000; max=2*maxn-1; type node=record data:int64; prt,lch,rch:0..max; end; treetype=array[1..max]of node; var tree:treetype;n,i:longint;s:int64; procedure hufm(var tree:treetype); var k,i,j:longint; function min(h:integer):integer; var i,p:longint;m1:int64; begin m1:=9223372036854775807; for p:=1 to h do if (tree[p].prt=0)and(m1>tree[p].data) then begin i:=p;m1:=tree[p].data; end; min:=i; end; begin fillchar(tree,sizeof(tree),0); for i:=1 to n do read(tree[i].data); for k:=n+1 to 2*n-1 do begin i:=min(k-1);tree[i].prt:=k;tree[k].lch:=i; j:=min(k-1);tree[j].prt:=k;tree[k].rch:=j; tree[k].data:=tree[i].data+tree[j].data; end; end; begin readln(n); hufm(tree); for i:=n+1 to 2*n-1 do s:=s+tree[i].data; writeln(s); end.
根据老师的建议,每次选出最小元素,与第二小的元素合并到一堆,这样每次都可以缩小范围,只需把每次合并耗费的体力值相加即可得到答案.
程序用一个长度为10000的数组,每次找到最小的元素,把它和最后一个元素交换,然后范围缩小1,之后再次寻找最小的元素,两元素相加即可.
代码如下:
var n,i,x,y,s:longint; a:array[1..10000]of longint; procedure swap(var a,b:longint); var t:longint; begin t:=a; a:=b; b:=t; end; function min(n:longint):longint; var i,p,q:longint; begin p:=maxlongint; for i:=1 to n do if a[i]<p then begin p:=a[i]; q:=i; end; min:=q; end; begin s:=0; readln(n); for i:=1 to n do read(a[i]); while n>1 do begin x:=min(n);swap(a[n],a[x]);dec(n); y:=min(n);a[y]:=a[y]+a[n+1]; s:=s+a[y]; end; writeln(s); end.
相比第一种方法,效率提高了很多,10个数据全部通过,但相比之下,还是第三种方法效率高(老师想出来的,貌似运用的贪心算法),效率再次提高.
代码如下:
var a,b:array[1..10002]of longint; x,y,y1,n,i,s:longint; procedure sort(l,r: longint); var i,j,x,y: longint; begin i:=l; j:=r; x:=a[(l+r) div 2]; repeat while a[i]<x do inc(i); while x<a[j] do dec(j); if not(i>j) then begin y:=a[i];a[i]:=a[j];a[j]:=y; inc(i);j:=j-1; end; until i>j; if l<j then sort(l,j); if i<r then sort(i,r); end; begin readln(n); s:=0; for i:=1 to 10002 do begin a[i]:=maxlongint; b[i]:=maxlongint; end; for i:=1 to n do read(a[i]); sort(1,n); x:=1;y:=1;y1:=1; while y1<n do if (a[x+1]<=b[y]) then begin b[y1]:=a[x]+a[x+1];inc(x,2); inc(y1);end else if a[x]>=b[y+1] then begin b[y1]:=b[y]+b[y+1]; inc(y1);inc(y,2); end else begin b[y1]:=b[y]+a[x]; inc(x);inc(y);inc(y1); end; for i:=1 to n-1 do s:=s+b[i]; writeln(s); end.
标签:des style c class blog code
原文地址:http://www.cnblogs.com/cuichen/p/3754217.html