Codeforces Round #704 (Div. 2)C. Maximum width

												C. Maximum width
									       	time limit per test2 seconds
								    	memory limit per test512 megabytes
												inputstandard input
											   outputstandard output

Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: s of length n and t of length m.

A sequence p1,p2,…,pm, where 1≤p1<p2<…<pm≤n, is called beautiful, if spi=ti for all i from 1 to m. The width of a sequence is defined as max1≤i<m(pi+1−pi).

Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings s and t there is at least one beautiful sequence.

Input
The first input line contains two integers n and m (2≤m≤n≤2⋅105) — the lengths of the strings s and t.

The following line contains a single string s of length n, consisting of lowercase letters of the Latin alphabet.

The last line contains a single string t of length m, consisting of lowercase letters of the Latin alphabet.

It is guaranteed that there is at least one beautiful sequence for the given strings.

Output
Output one integer — the maximum width of a beautiful sequence.

题意:

在s中找t的每一个字符,求t中的相邻字符在s中的最大间距。

思路:

分别顺序和倒叙遍历s得到t中每一个字符在s中的位置的最大最小值,最后看t中每一个字符的最大位置与它上一个字符的最小位置的距离最大值是多少。

#include<bits/stdc++.h>
using namespace std;
 #define ll long long
 const int mod = 1e9 + 7;
char s[200010],t[200010];
int maxx[200010],minn[200010];
 

int main()
{
    
    

	int n,m;
	scanf("%d%d",&n,&m);
	scanf("%s",s);
	scanf("%s",t);
	int k = 0;
	for(int i = 0; i < n; i++)
	{
    
    
		if(s[i] == t[k])
		{
    
    
			minn[k++] = i;
		}
	}
	k = m - 1;
	for(int i = n - 1; i >= 0; i--)
	{
    
    
		if(s[i] == t[k])
		{
    
    
			maxx[k--] = i;
		}
	}
	int maxxx = 0;
	for(int i = 0; i < m - 1; i++)
	{
    
    
		maxxx = max(maxxx, maxx[i + 1] - minn[i]);
	}
	printf("%d\n",maxxx);
}

猜你喜欢

转载自blog.csdn.net/p15008340649/article/details/114030981