J. Similarity (Easy Version) 2023 Jiangsu Collegiate Programming Contest, 2023 National Invitational

Problem - J - Codeforces

题目大意:有n个字符串,问这些字符串两两匹配的最长公共子串的最大长度是多少

思路:对于两个字符串s1,s2,令dp[i][[j]表示s1的前i个字符和s2的前j个字符中的最长公共字串的长度,遍历s1同时遍历s2,如果当前遍历到的两字符相同,那么就从两个字符串的上一个位置转移过来+1,dp[i][j]=dp[i-1][j-1]+1,否则dp[i][j]=0,dp[i][j]的最大值记为最长公共子串的长度

#include<bits/stdc++.h>
//#include<__msvc_all_public_headers.hpp>
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
const int N = 1e5 + 10, M = 2e5 + 10;
const ll INF = 1e18;
int n;
ll dp[55][55];
string s[55];
void init()
{
	for (int i = 0; i <= 50; i++)
	{
		dp[i][0] = dp[0][i] = 0;
	}
}
ll lcs(string x1, string x2)
{
	init();
	ll ret = 0;
	for (int i = 1; i < x1.length(); i++)
	{
		for (int j = 1; j < x2.length(); j++)
		{//两个字符串逐个位置遍历
			if (x1[i] == x2[j])
			{//相等就从上一个位置+1
				dp[i][j] = dp[i - 1][j - 1] + 1;
			}
			else
				dp[i][j] = 0;
			ret = max(ret, dp[i][j]);
		}
	}
	return ret;
}
void solve()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> s[i];
		s[i].insert(s[i].begin(), '#');//令字符串从1开始
	}
	ll ans = 0;
	for (int i = 1; i <= n; i++)
	{
		for (int j = i + 1; j <= n; j++)
		{
			ans = max(ans, lcs(s[i], s[j]));//维护最大值
		}
	}
	cout << ans << '\n';
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	//t = 1;
	while (t--)
	{
		solve();
	}
	return 0;
}
 

猜你喜欢

转载自blog.csdn.net/ashbringer233/article/details/134063756