poj 1159 (DP LCS)

本文介绍了一种使用滚动数组实现的最长公共子序列(LCS)算法,并通过一个具体示例展示了如何计算字符串与其反转字符串的LCS长度,进而求得最小编辑距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

滚动数组 + LCS

 1 // File Name: 1159.cpp
 2 // Author: Missa_Chen
 3 // Created Time: 2013年07月08日 星期一 10时07分13秒
 4 
 5 #include <iostream>
 6 #include <string>
 7 #include <algorithm>
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cmath>
11 #include <queue>
12 #include <map>
13 #include <stack>
14 #include <set>
15 #include <cstdlib>
16 #include <vector>
17 #include <time.h>
18 
19 using namespace std;
20 
21 const int maxn = 5e3 + 5;
22 int n;
23 char buf[maxn];
24 int LCS(string s1, string s2)
25 {
26     int dp[2][maxn] = {0};
27     int e = 0;
28     for (int i = 1; i <= n; ++i)
29     {
30         e = 1 - e;
31         for (int j = 1; j <= n; ++j)
32             if (s1[i - 1] == s2[j - 1])
33                 dp[e][j] = dp[1 - e][j - 1] + 1;
34             else dp[e][j] = max (dp[1 - e][j], dp[e][j - 1]);
35     }
36     return dp[e][n];
37 }
38 int main()
39 {
40     while (~scanf("%d",&n))
41     {
42         scanf("%s", buf);
43         string s, rev;
44         s = rev = buf;
45         reverse(rev.begin(), rev.end());
46         printf("%d\n", n - LCS(s, rev));
47     }
48     return 0;
49 }

 

转载于:https://www.cnblogs.com/Missa/p/3178977.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值