Codeforces Round 972 (Div. 2) C

kanade16發表於2024-09-27
#include <bits/stdc++.h>
using namespace std;
const int N = 1 * 1010;
const int MN = - N * N - 10;
const char cc[6] = {'n','a','r','e','k'};
string s[N];
int dp[6][2];
int T,n,m;
int pre(int x)
{
	return (x + 1) % 2;
}
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&m);
		for(int i = 1;i <= n;i++)
			cin >> s[i];
		int now = 0;
		for(int i = 0;i < 5;i++)
			dp[i][now] = MN;
		dp[4][now] = 0;
		for(int k = 1;k <= n;k++)
		{
			int sum = 0;
			for(int i = 0;i < m;i++)
			{
				int flag = 0;
				for(int j = 0;j < 5;j++)
					if(s[k][i] == cc[j])
						flag = 1;
				sum += flag;
			}
			now = (now + 1) % 2; //
			for(int i = 0;i < 5;i++)
				dp[i][now] = dp[i][pre(now)];
			int nxt;
			for(int bg = 0;bg < 5;bg++)
			{
				if(dp[bg][pre(now)] == MN)continue;
				nxt = (bg + 1) % 5;
				int count = 0;
				for(int j = 0;j < m;j++)
				{
					if(s[k][j] == cc[nxt])
					{
						count ++;
						dp[nxt][now] = max(dp[nxt][now] ,dp[bg][pre(now)] + count - (sum - count));
						nxt = (nxt + 1) % 5;
					}
				}
			}
		}
		int ans = -1;
		for(int i = 0;i < 5;i++)
			ans = max(ans,dp[i][now] - ((i + 1) % 5) * 2);
		printf("%d\n",ans);
	}
	return 0;
}

相關文章