procedure2012
It's not worth it to know you're not worth it!

[题目来源]:IOI 2000

[关键字]:动态规划

[题目大意]:把一个字符串变成回文串所需的最小步骤。

//=====================================================================================================

[分析]:因为回文串的要求是正着读和倒着读是一样的,即把这个字符串倒置后进行匹配,用动态规划求出所需最小操作数。f[i,j]={f[i-1,j-1]|s1[i]=s2[j],min{f[i-1,j],f[i,j-1]+1|s1[i]<>s2[j]}}。但是最后要除以二,因为两个字符串其实是同一个,所以所有操作都会被计算两次(自己模拟一下)。

[代码]:

View Code
 1 program Project1;
2 var
3 n: longint;
4 f: array[0..5010,0..5010] of integer;
5 s1, s2: ansistring;
6
7 procedure init;
8 var
9 i: longint;
10 begin
11 readln(n);
12 readln(s1);
13 s2 := '';
14 for i := n downto 1 do
15 s2 := s2+s1[i];
16 //writeln(s1,'#',s2,'@');
17 //readln;
18 //readln;
19 end;
20
21 function min(x, y: longint):longint;
22 begin
23 if x < y then exit(x) else exit(y);
24 end;
25
26 procedure work;
27 var
28 i, j, st: longint;
29 begin
30 fillchar(f,sizeof(f),0);
31 for i := 1 to n do
32 begin
33 f[i,0] := i;
34 f[0,i] := i;
35 end;
36 for i := 1 to n do
37 for j := 1 to n do
38 begin
39 if s1[i] = s2[j] then begin f[i,j] := f[i-1,j-1]; continue; end;
40 f[i,j] := min(f[i-1,j],f[i,j-1])+1;
41 end;
42 writeln(f[n,n] shr 1);
43 readln;
44 end;
45
46 begin
47 init;
48 work;
49 end.



posted on 2011-11-02 08:07  procedure2012  阅读(186)  评论(0编辑  收藏  举报