hdu1159 (简单dp)

来源:互联网 发布:淘宝女鞋图片 编辑:程序博客网 时间:2024/06/03 17:47

Common Subsequence

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


题目分析:

求LIS,简单dp, 状态表示:dp[i][j]表示两个串分别到i,j位置为止的最大长度,状态转移if(a[i]==b[j]] dp[i][j]=dp[i-1][j-1]+1。


代码:

#include <iostream>#include <sstream>#include <ios>#include <iomanip>#include <functional>#include <algorithm>#include <vector>#include <string>#include <list>#include <queue>#include <deque>#include <stack>#include <set>#include <map>#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <climits>#include <cctype>using namespace std;#define XINF INT_MAX#define INF 0x3FFFFFFF#define MP(X,Y) make_pair(X,Y)#define PB(X) push_back(X)#define REP(X,N) for(int X=0;X<N;X++)#define REP2(X,L,R) for(int X=L;X<=R;X++)#define DEP(X,R,L) for(int X=R;X>=L;X--)#define CLR(A,X) memset(A,X,sizeof(A))#define IT iterator#define max(a,b) (a>b)?a:b#define min(a,b) (a<b)?a:btypedef long long ll;typedef pair<int,int> PII;typedef vector<PII> VII;typedef vector<int> VI;const int maxn=1000;int dp[maxn][maxn];char a[maxn],b[maxn];int main(){int n,m;while(scanf("%s%s",a,b)!=EOF){memset(dp,0,sizeof(dp));int ans=0;n=strlen(a);m=strlen(b);    for(int i = 0; i < n; i++) {       for(int j = 0; j < m; j++) {         if(a[i] == b[j]) {            if(i > 0 && j > 0) dp[i][j] = dp[i-1][j-1] + 1;         else dp[i][j] = 1;  }         if(i > 0) dp[i][j] = max(dp[i][j], dp[i-1][j]);         if(j > 0) dp[i][j] = max(dp[i][j], dp[i][j-1]);        }}     for(int i = 0; i < n; i++)for(int j=0;j<m;j++)           ans = max(ans, dp[i][j]);    cout<<ans<<endl;}return 0;}


0 0
原创粉丝点击