时间限制:1 秒

内存限制:32 兆

特殊判题:否

提交:2303

解决:1241

题目描述:

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.

样例输入:
abcd
cxbydz
样例输出:
2
来源:
2008年上海交通大学计算机研究生机试真题

思路:

动态规划,分别设置两个指针,分别从头到尾搜索两个数组,最后得到的就是最大值。

动态规划的关键方程是:

if(a[i]
== b[j])
    res[i+1][j+1]
= res[i][j]+1;
else
    res[i+1][j+1]
= max(res[i+1][j], res[i][j+1]);

代码:

#include <stdio.h>
#include <string.h> #define N 100
#define max(a, b) (((a)>(b)) ? (a) : (b)) int main(void)
{
int na, nb, i, j;
char a[N+1], b[N+1];
int res[N+1][N+1]; while (scanf("%s%s", a, b) != EOF)
{
na = strlen(a);
nb = strlen(b);
memset(res, 0, sizeof(res));
for (i=0; i<na; i++)
{
for (j=0; j<nb; j++)
{
if (a[i] == b[j])
res[i+1][j+1] = res[i][j]+1;
else
res[i+1][j+1] = max(res[i+1][j], res[i][j+1]);
}
}
/*
for (i=1; i<=na; i++)
{
for (j=1; j<=nb; j++)
{
printf("%d ", res[i][j]);
}
printf("\n");
}
*/
printf("%d\n", res[na][nb]);
} return 0;
}
/**************************************************************
Problem: 1042
User: liangrx06
Language: C
Result: Accepted
Time:0 ms
Memory:912 kb
****************************************************************/

最新文章

  1. C# 表复制和数据行的复制说明(Clone、ImportRow 、Copy )
  2. [转载]MySQL5.5 配置文件 my.ini 1067错误
  3. python suds 一坑
  4. PHP模拟登录并获取数据
  5. ORA-12631 / TNS-12631: Username retrieval failed
  6. 解决fontawesome-webfont 被拦截的问题
  7. 成为Java GC专家(4)—Apache的MaxClients参数详解及其在Tomcat执行FullGC时的影响
  8. Codevs 1697 ⑨要写信
  9. Bitmap 与Drawable相互转换
  10. WPF Customize TabControl
  11. shu_1186 字符排列问题
  12. data按钮
  13. linux shell编程指南第十八章------控制流结构
  14. centos下chm阅读器
  15. 【LeetCode每天一题】Swap Nodes in Pairs
  16. bind的封装
  17. ImportError: sys.meta_path is None, Python is likely shutting down
  18. JDBC方式执行SQL,支持CRUD返回LIST
  19. 怎样将Android SDK源码 导入到Eclipse中?
  20. 39 - 同步-异步-IO多路复用

热门文章

  1. 【WEB基础】HTML &amp; CSS 基础入门(8)表单
  2. [置顶] pycurl检测网站性能,pycurl.*_TIME时间问题
  3. Android性能专项测试之耗电量统计API
  4. js传递默认形参
  5. 重读金典------高质量C编程指南(林锐)-------第二章 程序的板式
  6. java equals与==区别
  7. (九)jQuery中的动画(载)
  8. Javascript模式(三) 策略模式
  9. Maven自动生成web.xml配置文件
  10. android开发系列之数据存储