首页 > 代码库 > POJ 3356 AGTC(DP求字符串编辑距离)

POJ 3356 AGTC(DP求字符串编辑距离)

给出两个长度小于1000的字符串,有三种操作,插入一个字符,删除一个字符,替换一个字符。

问A变成B所需的最少操作数(即编辑距离)

考虑DP,可以用反证法证明依次从头到尾对A,B进行匹配是不会影响答案的

令dp[i][j]表示A[i]~[lenA]变成B[j]~[lenB]的最优解。

如果把B[j]插入到A[i]前,dp[i][j]=dp[i][j+1]+1

如果删除A[i],dp[i][j]=dp[i+1][j]+1.

如果A[i]==B[j], dp[i][j]=dp[i+1][j+1].

如果A[i]!=B[j], 则用B[j]替换A[i]. dp[i][j]=dp[i+1][j+1]+1.

得出状态转移方程后记搜一下就OK了。

 

技术分享
# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-3
# define MOD 100000007
# define INF 1000000000
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<1,l,mid
# define rch p<<1|1,mid+1,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
    int res=0, flag=0;
    char ch;
    if((ch=getchar())==-) flag=1;
    else if(ch>=0&&ch<=9) res=ch-0;
    while((ch=getchar())>=0&&ch<=9)  res=res*10+(ch-0);
    return flag?-res:res;
}
void Out(int a) {
    if(a<0) {putchar(-); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+0);
}
const int N=1005;
//Code begin...

int dp[N][N], len1, len2;
char s1[N], s2[N];

int dfs(int x, int y)
{
    if (~dp[x][y]) return dp[x][y];
    if (x==len1&&y==len2) return 0;
    if (x==len1) return len2-y;
    if (y==len2) return len1-x;
    int ans=dfs(x+1,y)+1;
    ans=min(ans,dfs(x+1,y+1)+(s1[x]==s2[y]?0:1));
    ans=min(ans,dfs(x,y+1)+1);
    return dp[x][y]=ans;
}
int main ()
{
    while (~scanf("%d%s%d%s",&len1,s1,&len2,s2)) {
        mem(dp,-1);
        printf("%d\n",dfs(0,0));
    }
    return 0;
}
View Code

 

POJ 3356 AGTC(DP求字符串编辑距离)