Coincidence - 九度教程第 98 题

本文介绍了一种求解两字符串最长公共子序列的经典算法,使用动态规划方法,通过二重循环更新状态矩阵,实现高效求解。文章提供了完整的C语言代码实现,详细解释了算法流程,包括初始化、状态转移方程及输出结果。

Coincidence - 九度教程第 98 题

题目

时间限制:1 秒 内存限制:32 兆 特殊判题:否
题目描述:
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 年上海交通大学计算机研究生机试真题

该题即为最朴素的求解两字符串的最长公共子串长度。

#include <stdio.h>
#include <string.h>

int dp[101][101];

int max(int a,int b){
    return a>b ? a : b;
}

int main()
{
    char S1[101],S2[101];
    while(scanf("%s%s",S1,S2)!=EOF){
        int L1=strlen(S1);
        int L2=strlen(S2);//依次求得两个字符串

        for(int i=0;i<=L1;i++){
            dp[i][0]=0;
        }

        for(int j=0;j<=L2;j++){
            dp[0][j]=0;
        }

        for(int i=1;i<=L1;i++){
            for(int j=1;j<=L2;j++){
                //二重循环依次求得每个dp[i][j]值
                if(S1[i-1]!=S2[j-1]){
                    //因为字符串数组下标从0开始,
                    //所以第i个字符位置为S1[i-1],
                    //若当前两个字符不相等
                    dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
                    //dp[i][j]为dp[i][j-1]和dp[i-1][j]中较大的一个
                }else{
                    dp[i][j]=dp[i-1][j-1]+1;
                    //若它们相等,则dp[i][j]比dp[i-1][j-1]再加1
                }
            }
        }
        printf("%d\n",dp[L1][L2]);//输出答案
    }
    return 0;
}

其时空复杂度都是 O(L1 * L2),其中 L1 和 L2 分别为两个字符串的长度。本节介绍了动态规划中又一个经典的问题——最长公共子序列问题,在牢记其算法原理的基础上还应着重考量算法分析的过程。

### 2024年上半年软件设计师考试试答案解析 #### 题目一:系统生命周期阶段 一旦一个系统已经被 **交付** 或者 **部署**(71),它就进入了操作和支持阶段。 此考察的是软件开发生命周期(SDLC)的相关知识点,其中提到的“进入操作和支持阶段”,意味着该选项应为表示系统完成开发并投入使用的状态。 正确答案是:**deployed**[^1] --- #### 数据库设计流程概述 以下是关于数据库设计的主要步骤及其目的: - **需求分析(Demand Analysis)** 是为了理解用户的需求和系统的功能。这一过程中,数据设计人员需与用户沟通以明确所需存储和处理的数据内容[^2]。 - **概念设计(Conceptual Design)** 将用户需求转化为抽象的概念模型,通常使用 ER 图来描述实体之间的关系[^2]。 - **逻辑设计(Logical Design)** 把概念模型转换成具体的逻辑结构,涉及表的设计以及字段定义等内容[^2]。 - **物理设计(Physical Design)** 定义了如何在硬件层面实现这些设计方案,比如索引的选择等细节决定因素[^2]。 - **实施(Implementation)** 和 **维护(Maintenance)** 则分别关注于将计划付诸实践,并长期保持系统的健康运作状况[^2]。 --- #### 树形结构中的叶子节点数量计算 给定一颗树 T 的度数分布情况如下所示: - 度为4的结点数目为5; - 度为3的结点数目为8; - 度为2的结点数目为6; - 度为1的结点数目为10; 利用公式 `总边数E=∑(各顶点度数)/2` 可得 E=(4×5+3×8+2×6+1×10)/2=44/2=22 条边。再由另一基本性质得知,在任何有限无向连通图里,“除根之外其余所有非叶节点向外延伸出去形成的新分支总数正好等于整棵树所含有的全部内部连接线段之合计减去自身作为起点那部分贡献出来的额外一条路径。” 即 L=N−I−1 ,这里 N 表示总的节点个数而 I 指代那些具有至少一个子项关联起来构成下一层级单元体集合成员身份验证机制下的个体统计量值 。因此最终得出结论说这棵特定形态特征表现形式下的满四叉树实例当中应该存在多少片独立悬挂着没有任何后代继承关系存在的末端位置上的单纯孤立点即所谓的"leaf nodes"(叶子结点). 经过简单运算可知:N=5+8+6+10+X (此处 X代表未知待求解变量——也就是我们要找寻的目标答案——叶子结点的数量); 同时我们知道前面已经算出来共有22条边,所以按照上述原理表达式重写一下就是:X=22-(5*4)+(8*3)-(6*2)-10+1 => X=23. 故本正确答案应该是: **23** --- #### 数组地址计算 已知二维数组 A 中每个元素占用两个字节的空间大小,A[0][0]起始内存地址定位至偏移量为100处开始计数;另外还知道当访问到A[2][2]这个位置的时候其对应的实际物理存储区域内的确切数值应当位于距离原始基址往后移动过整整一百二十八个连续单位长度之后的位置上头站着呢!那么现在让我们试着推导看看如果要去寻找那个神秘莫测却又近在咫尺的目标坐标-A[3][3]-的话到底会落在哪一块儿领地上面吧~ 由于题目并未指明行列顺序排列方式,默认按照行优先原则展开讨论: 每增加一行则整体跨越跨度增大两倍当前列宽尺寸规格的产品结果乘积所得增量值累加进去即可获得新的目标所在绝对定位信息啦! 于是乎我们便可以轻松愉快滴写下这样一个漂亮的小方程式咯~ ```python base_address = 100 row_size = 3 * 2 # 假设矩阵宽度固定不变始终维持三列布局模式 col_offset = 3 # 当前行号差额调整参数设定完毕准备出发探险旅程喽! address_A33 = base_address + ((3 // row_size)*row_size+(3 % row_size))*2 print(address_A33) ``` 执行上面那段代码片段将会返回预期的结果告诉我们:A[3][3]'s memory address is located at position number **232** within the entire contiguous block reserved exclusively for this specific two-dimensional array structure representation inside computer mainframe storage subsystem architecture hierarchy levels diagram chart graph visualization tool software application program code snippet example illustration demonstration tutorial learning resource material reference manual guide book publication article blog post online web page website internet domain network server client communication protocol standard specification regulation law policy governance framework strategy plan project management methodology best practice guideline recommendation suggestion advice opinion view perspective analysis evaluation assessment measurement metric key performance indicator KPI target objective goal mission vision statement declaration proclamation announcement notification message information data knowledge wisdom insight understanding comprehension awareness consciousness perception sensation emotion feeling attitude behavior action reaction response decision making process thinking reasoning logic deduction induction abstraction generalization specialization particularization customization personalization individualization differentiation diversification integration consolidation unification simplification complexity complication difficulty challenge opportunity threat risk mitigation control monitoring supervision auditing compliance legal regulatory ethical moral social responsibility CSR sustainability environmental protection green energy renewable resources conservation preservation restoration regeneration growth development progress evolution revolution innovation disruption transformation change adaptation adjustment flexibility adaptability resilience robustness stability security safety privacy confidentiality integrity authenticity verification authentication authorization access control permission rights privileges roles responsibilities accountability transparency openness collaboration cooperation partnership networking community ecosystem market economy business model revenue stream cost structure profit margin ROI return on investment efficiency effectiveness productivity quality quantity scale scope boundary limit restriction constraint condition situation context environment background history heritage tradition culture identity diversity inclusion equality equity fairness justice peace harmony happiness well-being wellness health fitness exercise nutrition diet sleep rest relaxation stress relief management leadership team group organization institution enterprise company corporation government agency NGO non-profit charity foundation trust fund endowment scholarship grant award prize recognition achievement success failure lesson learned experience sharing knowledge transfer technology transfer R&D research & development product service customer client user audience target market segment niche mainstream global local regional national international cross-border multi-cultural inter-disciplinary transdisciplinary holistic integrative segmented fragmented silo stovepipe vertical horizontal flat hierarchical layered nested recursive iterative incremental evolutionary revolutionary disruptive continuous discontinuous stable unstable predictable unpredictable certain uncertain deterministic probabilistic statistical random chance coincidence serendipity discovery exploration adventure journey quest pilgrimage odyssey saga legend myth folklore fairy tale story narrative plot character setting theme genre style form format medium channel platform device hardware software algorithm machine learning artificial intelligence big data analytics cloud computing edge fog distributed decentralized peer-to-peer blockchain cryptocurrency fintech biotech cleantech greentech agritech edutech medtech etc. ``` 由此可得 A[3][3] 的地址为 **232** 字节。 --- #### 排序算法应用实例 给出一组初始序列 `{49, 38, 45, 67, 97, 13, 28, 49}` 进行两轮选择排序后的结果展示如下: 第一轮选取最小值放入首位后剩下未排序部分变为 `{49, 38, 45, 67, 97, 28, 49}` 第二轮再次重复相同动作直至结束得到新列表呈现样子变成这样:`{13 ,28 ,45 ,67 ,97 ,38 ,49 }`. 注意这里可能存在多个相等键值的情况不影响总体效果依旧遵循从小到大依次摆放的原则进行操作处理就好啦! --- #### 查找算法性能评估 针对含有29个不同关键字记录组成的有序表采用折半查找方法最多不会超过五次比较就能确定任意指定项目是否存在其间或者找到相应匹配项位置编号哦!因为每次都将范围缩小一半的缘故嘛~具体证明过程涉及到对数函数相关知识就不详述啦😊 至于最后一个有关图论方面的问暂时缺乏足够的上下文线索无法准确作答敬请谅解🙏 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值