program tt; var n,i,l,j,k,ans:longint; a:array[1..300]of longint; f:array[1..300,1..300]of longint; function max(a,b:longint):longint; begin if a<b then max:=b else max:=a; end; begin read(n); for i:=1 to n do begin read(a[i]); a[n+i]:=a[i]; f[i,i]:=0; f[n+i,n+i]:=0; end; for i:=2*n-1 downto 1 do//起始位置,倒着循环可以让求f[i,j]所要用到的状态都用到 for j:=i+1 to i+n-1 do //终止位置 for k:=i to j-1 do //注意这里是到j-1,因为f[i,j]最多i=j 为0 f[i,j]:=max(f[i,j],f[i,k]+f[k+1,j]+a[i]*a[k+1]*a[j+1]); ans:=0; for i:=1 to n do ans:=max(ans,f[i,n+i-1]); writeln(ans); end.
f[i,j]=max{f[i,k]+f[k+1,j]+a[i]*a[k+1]*a[j+1]}
循环有两种写法:
program tt; var n,i,l,j,k,ans:longint; a:array[1..300]of longint; f:array[1..300,1..300]of longint; function max(a,b:longint):longint; begin if a<b then max:=b else max:=a; end; begin read(n); for i:=1 to n do begin read(a[i]); a[n+i]:=a[i]; f[i,i]:=0; f[n+i,n+i]:=0; end; for l:=2 to n do for i:=1 to 2*n do begin j:=i+l-1; if j<2*n then for k:=i to j-1 do f[i,j]:=max(f[i,j],f[i,k]+f[k+1,j]+a[i]*a[k+1]*a[j+1]); end; for i:=1 to n do ans:=max(ans,f[i,i+n-1]); writeln(ans); readln;readln; end.
第二种: