HDOJ 1159

编程入门 行业动态 更新时间:2024-10-10 10:23:10

<a href=https://www.elefans.com/category/jswz/34/1769005.html style=HDOJ 1159"/>

HDOJ 1159

题目链接:.php?pid=1159
题目如下:

Common Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 48342 Accepted Submission(s): 22226

Problem Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = <x1, x2, …, xm> another sequence Z = <z1, z2, …, zk> is a subsequence of X if there exists a strictly increasing sequence <i1, i2, …, ik> of indices of X such that for all j = 1,2,…,k, xij = zj. For example, Z = <a, b, f, c> is a subsequence of X = <a, b, c, f, b, c> with index sequence <1, 2, 4, 6>. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
这是一道非常非常经典的动态规划问题,求不连续的最长公共子序列,堪比背包问题。本人动态规划的水平也只能做做这样的题目了。有时候状态转移方程是真的难找。朴素的dp,空间为二维,如果数据太大,会爆内存,但是这个题目要求不高
ac代码如下:

#include<iostream>
#include<cstring>
#include<string>
using namespace std;int dp[1005][1005];int main(){string s1,s2;while(cin>>s1>>s2){int len1=s1.length();int len2=s2.length();int max_l=0;memset(dp,0,sizeof(dp));for(int i=1;i<=len1;i++){for(int j=1;j<=len2;j++){if(s1[i-1]==s2[j-1])  dp[i][j]=dp[i-1][j-1]+1;  //状态 +1 else  dp[i][j]=max(dp[i][j-1],dp[i-1][j]);     //状态转移 }}printf("%d\n",dp[len1][len2]);}return 0;
}

利用滚动数组的空间优化,参照了大佬们的思路,pre[]记录i-1的状态,dp[]现在状态。

#include<iostream>
#include<cstring>
#include<string>
using namespace std;int dp[1005],pre[1005];int main(){string s1,s2;while(cin>>s1>>s2){int len1=s1.length();int len2=s2.length();memset(dp,0,sizeof(dp));memset(pre,0,sizeof(pre));for(int i=1;i<=len1;i++){for(int j=1;j<=len2;j++){if(s1[i-1]==s2[j-1])  dp[j]=pre[j-1]+1;else  dp[j]=max(dp[j-1],pre[j]);pre[j-1]=dp[j-1];  //pre记录i-1行,dp记录i行 }pre[len2]=dp[len2];}printf("%d\n",dp[len2]);}return 0;
}

更多推荐

HDOJ 1159

本文发布于:2024-02-06 10:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1748710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HDOJ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!