51nod 1183 编辑距离

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1183.

题意不再赘述。

分析:对于两个字符串s和t,dp[i][j]记录s的前i个字符转换到t的前j个字符的最小编辑距离。那么很容易得到转移方程 dp[i][j] = min(dp[i][j], dp[i-1][j-1] + s[i-1] == t[j-1] ? 0 : 1)。对每个dp[i][j],我们考虑直接从dp[i-1][j]或dp[i][j-1]加一个字符,所以初始为dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1。对于dp[0][i]和dp[i][0],显然都等于i。

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
using namespace std;

typedef long long LL;
#define mem(a, n) memset(a, n, sizeof(a))
#define ALL(v) v.begin(), v.end()
#define si(a) scanf("%d", &a)
#define sii(a, b) scanf("%d%d", &a, &b)
#define siii(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define pb push_back
#define eps 1e-8
const int inf = 0x3f3f3f3f, N = 1e3 + 5, MOD = 1e9 + 7;

int T, cas = 0;
int n, m;
int dp[N][N];
char s[N], t[N];

int main(){
#ifdef LOCAL
    freopen("/Users/apple/input.txt", "r", stdin);
//	freopen("/Users/apple/out.txt", "w", stdout);
#endif
	
    while(scanf("%s%s", s, t) != EOF) {
    	int n = strlen(s), m = strlen(t);
    	for(int i = 0; i <= n; i ++) dp[i][0] = i;
    	for(int i = 0; i <= m; i ++) dp[0][i] = i;
    	for(int i = 1; i <= n; i ++) {
    		for(int j = 1; j <=m; j ++) {
    			dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1;
    			dp[i][j] = min(dp[i][j], dp[i-1][j-1] + (s[i-1] != t[j-1]));
    		}
    	}
    	printf("%d\n", dp[n][m]);
    } 
    
    return 0;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yeluorag/article/details/49524915
文章标签: dp
个人分类: 动态规划
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭