您的位置:首页 > 其它

问题 C: 求最长上升序列

2015-07-10 09:46 225 查看

题目描述

设有由n个不相同的整数组成的数列,记为:b(1)、b(2)、……、b(n)且b(i)<>b(j) (i<>j),若存在i1<i2<i3< … < ie 且有b(i1)<b(i2)< … <b(ie)则称为长度为e的不下降序列。程序要求,当原数列出之后,求出最长的不下降序列。
例如13,7,9,16,38,24,37,18,44,19,21,22,63,15。例中13,16,18,19,21,22,63就是一个长度为7的不下降序列,同时也有7 ,9,16,18,19,21,22,63长度为8的不下降序列。

输入

只有一行,为若干正整数(最多1000个数)

输出

为两行,第一行为最上升序列的长度。第二行为该序列

样例输入

13 7 9 16 38 24 37 18 44 19 21 22 63 15

样例输出

max=8
7 9 16 18 19 21 22 63var i,m,j,sum,x:longint;b,f,t,a:array[1..10000]of longint; h:array[1..2]of integer;begin//assign(input,'input.txt');//assign(output,'output.txt');//reset(input);//rewrite(output);m:=0;while not eof dobegin m:=m+1; read(b[m]); f[m]:=1;end; {for i:=1 to m do begin f[i]:=1; t[i]:=1; end;} for i:=m-1 downto 1 do for j:=i+1 to m do if (b[i]<b[j]) and (f[i]<f[j]+1) then begin f[i]:=f[j]+1; a[i]:=j; end; h[1]:=0; for i:=1 to m do if f[i]>h[1] then begin h[1]:=f[i]; h[2]:=i; end; {for i:=m-1 downto 1 do begin sum:=0; for j:=i+1 to m do if (b[i]<=b[j]) and (f[i]=f[j]+1) then sum:=sum+t[j]; if sum>t[i] then t[i]:=sum; end; ans:=0; sum:=0; for i:=1 to m do if f[i]>ans then ans:=f[i]; for i:=1 to m do if f[i]=ans then sum:=sum+t[i]; } writeln('max=',h[1]);x:=b[h[2]]; for i:=1 to h[1] do begin write(x,' '); x:=b[a[h[2]]]; h[2]:=a[h[2]]; end; //close(input); //close(output);end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: