http://codeforces.com/contest/1203/problem/D2
D2. Remove the Substring (hard version)
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
bbaba
bb
outputCopy
3
inputCopy
baaba
ab
outputCopy
2
inputCopy
abcde
abcde
outputCopy
0
inputCopy
asdfasdf
fasd
outputCopy
3
贪心,用两个数组记录子数组每个字符第一次和最后一次出现位置,ans就是firstpos[i]-lastpos[i+1]中最大的,fpos是关键字CE了三发。。。我太难了。。。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char t[200005],s[200005];
int lent,lens,fos[200005],lpos[200005];
int main()
{
scanf("%s%s",s+1,t+1);
lent=strlen(t+1),lens=strlen(s+1);
int tmp=1;
for(int i=1;i<=lent;i++)
{
while(s[tmp]!=t[i])
tmp++;
fos[i]=tmp;
tmp++;
}
tmp=lens;
for(int i=lent;i>0;i--)
{
while(s[tmp]!=t[i])
tmp--;
lpos[i]=tmp;
tmp--;
}
int ans=0;
ans=max(ans,lpos[1]-1);
ans=max(ans,lens-fos[lent]);
for(int i=1;i<lent;i++)
ans=max(ans,lpos[i+1]-fos[i]-1);
printf("%d\n",ans);
}