此题有两解:
1.直接法:
由题可知:f[i,j]表示字串i到j部分的构成回文的最少添加字符数,所以
f[i,j]:=min(f[i+1,j]+1,f[i,j-1]+1,f[i+1,j-1]+ord(a[i]<>a[j])*2);
可递归求得。
但是由于此题的时间限制以及递归过程中调用函数缓慢,会导致部分数据超时。结果只有82分。
代码如下:
var
n,i,j:integer;
f:array[0..5001,0..5001]of integer;
a,b:array[0..5001]of char;
function find(i,j:integer):integer;
var
t1,t2,t3:longint;
begin
if f[i,j]<0 then
begin
if i>=j then f[i,j]:=0
else
begin
t1:=find(i+1,j)+1;
t2:=find(i,j-1)+1;
t3:=find(i+1,j-1)+ord(a[i]<>a[j])*2;
f[i,j]:=t1;
if f[i,j]>t2 then f[i,j]:=t2;
if f[i,j]>t3 then f[i,j]:=t3;
end;
end;
find:=f[i,j];
end;
begin
readln(n);
for i:=1 to n do read(a[i]);
fillchar(f,sizeof(f),255);
for i:=1 to n do f[i,i]:=0;
writeln(find(1,n));
end.
n,i,j:integer;
f:array[0..5001,0..5001]of integer;
a,b:array[0..5001]of char;
function find(i,j:integer):integer;
var
t1,t2,t3:longint;
begin
if f[i,j]<0 then
begin
if i>=j then f[i,j]:=0
else
begin
t1:=find(i+1,j)+1;
t2:=find(i,j-1)+1;
t3:=find(i+1,j-1)+ord(a[i]<>a[j])*2;
f[i,j]:=t1;
if f[i,j]>t2 then f[i,j]:=t2;
if f[i,j]>t3 then f[i,j]:=t3;
end;
end;
find:=f[i,j];
end;
begin
readln(n);
for i:=1 to n do read(a[i]);
fillchar(f,sizeof(f),255);
for i:=1 to n do f[i,i]:=0;
writeln(find(1,n));
end.
2.间接法:
题目可转换为,求字符串和这个字符串逆序的最大匹配子串长度,然后再与总长度求差,即为最少需添加字符构成回文串数。
f[i,j]:=f[i-1,j-1]+1;(a[i]=b[i])
f[i,j]:=min(f[i-1,j],f[i,j-1]);(a[i]<>b[i])
代码如下:
var
n,i,j,t1,t2,t3:integer;
f:array[0..5001,0..5001]of integer;
a,b:array[0..5001]of char;
begin
readln(n);
for i:=1 to n do
begin
read(a[i]);
b[n-i+1]:=a[i];
end;
fillchar(f,sizeof(f),0);
for i:=1 to n do
for j:=1 to n do
begin
if a[i]=b[j] then f[i,j]:=f[i-1,j-1]+1
else
if f[i-1,j]>f[i,j-1] then f[i,j]:=f[i-1,j]
else
f[i,j]:=f[i,j-1];
end;
writeln(n-f[n,n]);
end.
n,i,j,t1,t2,t3:integer;
f:array[0..5001,0..5001]of integer;
a,b:array[0..5001]of char;
begin
readln(n);
for i:=1 to n do
begin
read(a[i]);
b[n-i+1]:=a[i];
end;
fillchar(f,sizeof(f),0);
for i:=1 to n do
for j:=1 to n do
begin
if a[i]=b[j] then f[i,j]:=f[i-1,j-1]+1
else
if f[i-1,j]>f[i,j-1] then f[i,j]:=f[i-1,j]
else
f[i,j]:=f[i,j-1];
end;
writeln(n-f[n,n]);
end.