codeforces 1446B - Catching Cheaters (dp)

题目链接:https://codeforces.com/problemset/problem/1446/B

\(LCS\) 的改版, \(f[i][j]\) 表示以 \(i,j\) 结尾的最大答案,
如果 \(A[i] == B[j]\) ,那么贡献就会加 \(2\), 否则贡献会减 \(1\)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;

const int maxn = 5010;

int n, m;
int f[maxn][maxn];

char A[maxn], B[maxn];

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	n = read(), m = read();
	scanf("%s", A + 1); scanf("%s", B + 1);
	
	for(int i = 1 ; i <= n ; ++i){
		for(int j = 1 ; j <= m ; ++j){
			f[i][j] = max(f[i][j], f[i - 1][j] - 1);
			f[i][j] = max(f[i][j], f[i][j - 1] - 1);
			if(A[i] == B[j]){
				f[i][j] = max(f[i][j], f[i - 1][j - 1] + 2);
			}
		}
	}
	
	int ans = 0;
	for(int i = 1 ; i <= n ; ++i){
		for(int j = 1 ; j <= m ; ++j){
			ans = max(ans, f[i][j]); 
		}
	}
	
	printf("%d\n", ans);
	
	return 0;
}
posted @ 2020-11-19 18:26  Tartarus_li  阅读(88)  评论(0编辑  收藏  举报