Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.
Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6]then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".
Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.
It is guaranteed that the word p can be obtained by removing the letters from word t.
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t.
Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
Print a single integer number, the maximum number of letters that Nastya can remove.
ababcba abb 5 3 4 1 7 6 2
3
bbbabb bb 1 6 3 4 2 5
4
In the first sample test sequence of removing made by Nastya looks like this:
"ababcba" "ababcba" "ababcba" "ababcba"
Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".
So, Nastya will remove only three letters.
這個題在比賽中沒有想到用二分,0rzzz,但是下來一搜別人的博客是二分,就跑去把代碼敲了出來,可能是自己對二分的理解還不夠深刻吧。
code:
#include<cstring>
#include<cstdio>
const int MAXN=2e5+5;
char str1[MAXN],str2[MAXN];
int order[MAXN];
bool visit[MAXN];
int Len1,Len2;
bool C(int x){
memset(visit,false,sizeof(visit));
for(int i=0;i<x;++i)
visit[order[i]]=true;
int i=0,j=0;
for(;i<Len1&&j<Len2;++i){
if(!visit[i]){
if(str2[j]==str1[i])++j;
}
}
return j==Len2;
}
int main(){
scanf("%s%s",str1,str2);
Len1=strlen(str1);
Len2=strlen(str2);
for(int i=0;i<Len1;++i){
int a;scanf("%d",&a);
order[i]=a-1;
}
int lo=-1,hi=Len1+1;
while(hi-lo>1){
int mid=(hi+lo)/2;
if(C(mid))lo=mid;
else hi=mid;
}
printf("%d\n",lo);
}
Let's consider the first test case, where you have this order of deleting characters:
Let's write down if we could obtain the target word after deleting characters order[0], order[1], ... order[i] of the original word (Note that we always delete characters in this order):
This sequence is monotonous and thus, we could do a binary search to find the maximum index, which brings "YES". :)
Hope that helps!