天天看點

Codeforces Round #683 (Div. 2, by Meet IT)——D. Catching Cheaters

Codeforces Round #683 (Div. 2, by Meet IT)——D. Catching Cheaters

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.

思路: 用dp直接做,如果i==j,就說明這一個是可以使用的數,f[i][j]=max(0,f[i-1][j-1])+2,我們隻要判斷是直接從這個數重新開始還是連着前面繼續,加2是+4-1-1.如果i!=j,f[i][j]=max(f[i-1][j],f[i][j-1])-1;判斷一下是從上面的數組繼承來的大還是下面,然後減去一個長度就行了。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char a[10000],b[10000];
int f[6000][6000];
int main()
{
	int n,m;
	cin>>n>>m;
	cin>>a+1>>b+1;
	f[0][0]=0;
	int maxx=0;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(a[i]==b[j])
			{
				f[i][j]=max(0,f[i-1][j-1])+2;
			}else{
				f[i][j]=max(f[i-1][j],f[i][j-1])-1;
			}
			maxx=max(f[i][j],maxx);
		}
	}
	printf("%d\n",maxx);
} 
           

繼續閱讀