codeforces 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.

Examples

5 3
abbbc
abc

3

5 2
aaaaa
aa

4

题目大意

找到在s从左到右一些字母t。,问s中所有选中的字符中,最大间距是多少。

解题思路

以t中找到的字母为根据去寻找在s中所在字母的最前位置和最后位置,并对其坐标进行标记
然后遍历整个字符串,找到当前字母的最后位置和前一个字母的最前位置的差值,并取最大值

AC代码

#include <iostream>
#include <vector>
#include  <cstring>
using namespace std;
vector<int>fir,sec;
int main() {
    
    
	string s,t;
	int n,m;
	cin>>n>>m;
	getchar();
	getline(cin,s);
	getline(cin,t);
	for(int i=0,j=0; i<m; i++) {
    
    
		while(t[i]!=s[j]) j++;
		fir.push_back(j);
		j++;
	}
	for(int i=m-1,j=n-1; i>=0; i--) {
    
    
		while(t[i]!=s[j])j--;
		sec.push_back(j);
		j--;
	}
	int count=0;
	for(int i=0; i+1<m; i++)
		count=max(count,sec[m-1-i-1]-fir[i]);
	cout<<count;
}


猜你喜欢

转载自blog.csdn.net/qq_34832548/article/details/114016501