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

17 篇文章 0 订阅

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;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

timidcatt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值