Longest common subsequence

在这里插入图片描述
Problem Description
Given two sequences, find the length of the longest common subsequence (LCS). A subsequence is different from a substring, for the former need NOT be consecutive of the original sequence. For example, for “ABCD" and “AEFC", the longest common subsequence is “AC", and the length of it is 2.

Input
The first line of input is an integer N representing the pair number of sequences in this group test cases. (0<N<=100) For each test case, it contains two lines. The first line contains two integer L1 and L2, which represent the lengths of two sequences (0 < L1, L2 <= 1000). The second line consists of two sequences separated by a space. Each sequence consists of uppercase English characters only.

Output
Output file must contain N integers - each integer represents the length of the longest common subsequence of the given sequences.

#include <iostream>
#include<cstdio>
using namespace std;
#include<algorithm>
const int maxn = 1000 + 10;
char S[maxn], T[maxn];
int main()
{
	int dp[1001][1001];
	int N;
	int L1=0, L2=0;
	
	scanf("%d", &N);
	while (N--) {
		scanf("%d%d", &L1, &L2);
		scanf("%s%s", S, T);
		for (int i = 0; i <=L1; i++)
			for (int j = 0; j <= L2; j++) {
				if (i == 0 || j == 0)
					dp[i][j] = 0;
				else if (S[i-1] == T[j-1])
					dp[i][j] = 1 + dp[i - 1][j - 1];
				else
					dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
			}
		cout << dp[L1][L2] << endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值