效云 李
unread,Apr 9, 2009, 3:04:47 AM4/9/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to 编程爱好者天地
编辑距离问题:下面是我的代码,望大家多多指教,多练以后
// 动态规划-编辑距离问题.cpp : Defines the entry point for the console
application.
//
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
void calculate(vector<vector<int> >& f,vector<char> s1,vector<char>
s2,int s1length,int s2length)
{
int i,j;
for(i=0;i<s1length;i++)
{
f[i][0]=i;
}
for(j=0;j<s2length;j++)
{
f[0][j]=j;
}
for(i=1;i<s1length;i++)
{
for(j=1;j<s2length;j++)
{
int temp=f[i-1][j]+1;
if(temp>(f[i][j-1]+1))
{
temp=f[i][j-1]+1;
}
if(temp>f[i-1][j-1]+(s1[i]==s2[j]?0:1))
{
temp=f[i-1][j-1]+(s1[i]==s2[j]?0:1);
}
f[i][j]=temp;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int s1length,s2length;
ifstream finput;
finput.open("input.txt");
finput>>s1length;
vector<char> s1(s1length);
int i;
char temp;
for(i=0;i<s1length;i++)
{
finput>>temp;
s1[i]=temp;
}
finput>>s2length;
vector<char> s2(s2length);
for(i=0;i<s2length;i++)
{
finput>>temp;
s2[i]=temp;
}
finput.close();
vector<vector<int> > f(s1length,vector<int>(s2length));
calculate(f,s1,s2,s1length,s2length);
cout<<f[s1length-1][s2length-1];
/*for(i=0;i<s2length;i++)
{
cout<<s2[i]<<endl;
}
*/
system("pause");
return 0;
}