4228K 0MS GCC 568B 2009-01-09 11:00:31

注意:这道题目是多case。。。。害我在这上面wrong了n次。

数组best[i][j],第一个字符串前i位和第二个字符串前j位能做到的最优值。

分析:

1)a[i]==b[j],best[i][j]=best[i-1][j-1];

2)  a[i]!=b[j],best[i][j]=min(best[i-1][j-1],best[i-1][j],best[i][j-1])+1;

第一个元素:修改操作。第二个元素:删除操作。第三个元素:添加操作。

代码如下:

 

 process()
{
    int i,j;
    
for(i=0;i<=lena;i++)
        best[i][
0]=i;
    
for(j=1;j<=lenb;j++)
        best[
0][j]=j;
    
for(i=1;i<=lena;i++)
        
for(j=1;j<=lenb;j++){
            
if(a[i]==b[j])
                best[i][j]
=best[i-1][j-1];
            
else
                best[i][j]
=min(best[i-1][j-1],best[i-1][j],best[i][j-1])+1;
        }
    printf(
"%d\n",best[lena][lenb]);

}
int main()
{
    
while(scanf("%d %s",&lena,&a[1])!=EOF){
        scanf(
"%d %s",&lenb,&b[1]);
        process();
    }
    
return 0;
}

相关文章: