Codeforces Round #683 (Div. 2) D. Catching Cheaters(dp动态规划)

题目链接:https://codeforc.es/contest/1447/problem/D

You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅LCS(C,D)−|C|−|D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.

You believe that only some part of the essays could have been copied, therefore you’re interested in their substrings.

Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C,D) over all pairs (C,D), where C is some substring of A, and D is some substring of B.

If X is a string, |X| denotes its length.

A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.

Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.

You may wish to read the Wikipedia page about the Longest Common Subsequence problem.

Input
The first line contains two positive integers n and m (1≤n,m≤5000) — lengths of the two strings A and B.

The second line contains a string consisting of n lowercase Latin letters — string A.

The third line contains a string consisting of m lowercase Latin letters — string B.

Output
Output maximal S(C,D) over all pairs (C,D), where C is some substring of A, and D is some substring of B.

Examples

input

4 5
abba
babab

output

5

input

8 10
bbbbabab
bbbabaaaaa

output

12

input

7 7
uiibwws
qhtkxcn

output

0

分析

设 dp[i][j] 表示 a 字符串前 i 个和 b 字符串前 j 个的最大 4⋅LCS(C,D)−|C|−|D| 。

首先如果 ai 不等于 bj ,那么这个状态就会损失掉 1 (因为 4⋅LCS(C,D) 没变,而 C 或 D 的长度增大了 1),动态转移方程就为 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) - 1

若 ai 等于 bj ,那么这个状态就会增加 2 (同理,因为 4⋅LCS(C,D) 增加了 4 ,而 C 和 D 都增加了 1),动态转移方程就为 dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 2)

如果一个 dp[i][j] ,那我们还不如抛弃前面的,直接使其等于 0 ,dp[i][j] = max(dp[i][j], 0)

最后答案就是 dp[i][j] 中的最大值。

代码
#include<bits/stdc++.h>
using namespace std;

char a[5007],b[5007];
int dp[5007][5007];
int n,m,ans;

int main()
{
	scanf("%d%d",&n,&m);
	scanf("%s%s",a + 1, b + 1);
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
		{
			dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) - 1;
			if(a[i] == b[j]) dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 2);
			dp[i][j] = max(dp[i][j], 0);
			ans = max(ans, dp[i][j]);
		}
	printf("%d",ans);
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值