HDU - 1159 Common Subsequence (簡單LCS)

    HDU - 1159 Common Subsequence

題意:

    在兩個字符串x,y中,求它們最長的公共子串長度

分析:

    存在x[i] == y[j]時,則公共子串長度+1,否則,維護當前最大值

    狀態:dp[i][j]:表示以x[i], y[j]結尾時,最大公共子串的長度

    轉移方程:

            if(x[i] == y[j])        
                dp[i][j] = dp[i-1][j-1] + 1;
            else 
                dp[i][j] = max(dp[i][j-1], dp[i-1][j]);

核心:

for(i = 1; i<=len1; i++)
{
    for(j = 1; j<=len2; j++)
    {
        if(x[i] == y[j])
            dp[i][j] = dp[i-1][j-1] + 1;
        else 
            dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
    }
}

代碼:


#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <math.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#include <time.h>

using namespace std;

int dp[1000+10][1000+10];

int main()
{
    //freopen("a.txt", "r", stdin);

	int i, j;
	char str1[1000+10], str2[1000+10];
	while(~scanf("%s%s", str1+1, str2+1))
	{
		memset(dp, 0, sizeof(dp));
		for(i = 1; str1[i]; i++)
		{
			for(j = 1; str2[j]; j++)
			{
				if(str1[i] == str2[j])
					dp[i][j] = dp[i-1][j-1] + 1;
				else 
					dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
			}
		}
		printf("%d\n", dp[strlen(str1)-1][strlen(str2)-1]);
	}
    return 0;
}


發佈了29 篇原創文章 · 獲贊 1 · 訪問量 8177
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章