Codeforces 1203D2

D2. Remove the Substring (hard version)
The only difference between easy and hard versions is the length of the string.
You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s).
For example, the strings “test”, “tst”, “tt”, “et” and “” are subsequences of the string “test”. But the strings “tset”, “se”, “contest” are not subsequences of the string “test”.
You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s.
If you want to remove the substring s[l;r] then the string s will be transformed to s1s2…sl−1sr+1sr+2…s|s|−1s|s| (where |s| is the length of s).
Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s.
Input
The first line of the input contains one string s consisting of at least 1 and at most 2⋅105 lowercase Latin letters.
The first line of the input contains one string t consisting of at least 1 and at most 2⋅105 lowercase Latin letters.
It is guaranteed that t is a subsequence of s.
Output
Print one integer — the maximum possible length of the substring you can remove so that t is still a subsequence of s.
Examples
input bbaba bb output 3
input baaba ab output 2
input abcde abcde output 0
input asdfasdf fasd output 3
사고의 방향
제목은 문자열 s에서 가능한 한 큰 구간을 잘라서 t가 남은 문자열의 서열을 유지하도록 하는 것입니다.먼저 s를 앞뒤로 한 번 훑어보고 t의 모든 문자가 s에 있는 위치를 각각 기록하며 t의 모든 문자가 다 훑어보고 끝난다.왼쪽부터 옮겨다니면 가장 오른쪽 문자의 오른쪽 구간이 최대 오른쪽 구간이다.오른쪽에서 시작하면 가장 왼쪽 문자의 왼쪽 구간이 최대 왼쪽 구간이다.중간의 인접한 두 문자를 하나하나 분할점으로 삼아 중간의 최대 구간을 구한다.세 구간을 비교하다.eg :
asdfadbcfbsc adbc
L[0] = 0 L[1] = 2 L[2] = 6 L[3] = 7
R[0] = 11 R[1] = 9 R[2] = 5 R[3] = 4
코드
#include
#include
using namespace std;
const int maxn = 2e5+10;

char s[maxn],t[maxn];
int l[maxn],r[maxn];

int main() {
	cin >> s >> t;
	int s_len = strlen(s);
	int t_len = strlen(t);
	int lcnt = 0, rcnt = 0;
	for(int i=0;i<s_len;i++) {
		if(s[i] == t[lcnt]) {
			l[lcnt] = i;
			lcnt++;
		}
		if(lcnt == t_len) {
			break;
		}
	}
	for(int i=s_len-1;i>=0;i--) {
		if(s[i] == t[t_len-rcnt-1]) {
			r[rcnt] = i;
			rcnt++;
		}
		if(rcnt == t_len) {
			break;
		}
	}
	int ans = max(r[t_len-1],s_len-l[t_len-1]-1);
	for(int i=0;i<t_len-1;i++) {
		ans = max(ans,r[i]-l[t_len-i-2]-1);
	}
	cout << ans << endl;
}

/*
asdfadbcfbsc
adbc

answer: 6


aaaabbbb
ab

answer: 6
*/

제목 출처
Codeforces 1203D2

좋은 웹페이지 즐겨찾기