[九度OJ]1042Coincidence
来源:互联网 发布:免费数据库有哪些 编辑:程序博客网 时间:2024/06/07 03:52
- 题目描述:
Find a longest common subsequence of two strings.
- 输入:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
- 输出:
For each case, output k – the length of a longest common subsequence in one line.
- 样例输入:
abcdcxbydz
- 样例输出:
2
- 来源:
2008年上海交通大学计算机研究生机试真题
经典的LCS问题
LCS问题具有最优子结构性质,可以采用动态规划解决,递推公式如下:
a[i][j] = 0, i=0 或 j = 0
a[i-1][j-1]+1, i>0 且 j>0 且 s1[i-1]=s2[j-1]
max(a[i-1][j], a[i][j-1]), i>0 且 j>0 且 s1[i-1]!=s2[j-1]
#include <cstdio>#include <cstdlib>#include <iostream>using namespace std;int LCS(const string s1, const string s2) {int n = s1.length()+1;int m = s2.length()+1;int **a = new int*[n];for (int i = 0; i < n; ++i) {a[i] = new int[m];}for (int i = 0; i < n; ++i) {a[i][0] = 0;}for (int i = 0; i < m; ++i) {a[0][i] = 0;}for (int i = 0; i < s1.length(); ++i) {for (int j = 0; j < s2.length(); ++j) {if (s1[i] == s2[j]) {a[i+1][j+1] = a[i][j]+1;}else {a[i+1][j+1] = a[i+1][j]>a[i][j+1] ? a[i+1][j]:a[i][j+1];}}}int ans = a[s1.length()][s2.length()];free(a);return ans;}int main(int argc, char const *argv[]) {string s1, s2;while (cin >> s1 >> s2) {cout << LCS(s1, s2) << endl;}return 0;}
0 0
- 九度oj-1042-Coincidence
- [九度OJ]1042Coincidence
- 九度oj 题目1042:Coincidence
- 九度1042:Coincidence
- 九度[1042]-Coincidence
- 九度 oj 题目1042:Coincidence (LCS)
- 九度OJ-1042:Coincidence(最长公共子序列)
- 九度OJ 1042 Coincidence -- 动态规划(最长公共子序列)
- 九度OJ 1042 Coincidence (动态规划求最长公共子序列)
- 九度OJ 1042:Coincidence(公共子序列) (DP)
- 九度oj 1042
- 九度OJ 1042
- 题目1042:Coincidence
- 题目1042:Coincidence
- 题目1042:Coincidence
- 题目1042:Coincidence
- Coincidence
- Coincidence
- bzoj1003(dp+最短路spfa)这才是省选的题
- 学习三境界
- 在Eclipse中使用JUnit4进行单元测试(初级篇)
- JAX-RS入门 十一:HATEOAS
- glib-2.14升级
- [九度OJ]1042Coincidence
- In android studio,cannot load 2 facets-unknown facet type:android and android-gradle
- ios中修改状态栏颜色的方法
- 剑指offer(二.1)数据结构篇之数组
- Merge Intervals And Insert Interval -- Leetcode
- chrome Vimium plugin
- perl lwp 默认的请求头
- Eclipse无法以Debug模式运行
- JAX-RS入门 十二: 可伸缩的JAX-RS应用