CodeForces - 779D String Game
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
Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p
It is guaranteed that the word p can be obtained by removing the letters from word t.
InputThe first and second lines of the input contain the words 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).
OutputPrint a single integer number, the maximum number of letters that Nastya can remove.
Examples input Copyababcbaoutput Copy
abb
5 3 4 1 7 6 2
3input Copy
bbbabboutput Copy
bb
1 6 3 4 2 5
4Note
In the first sample test sequence of removing made by Nastya looks like this:
"ababcba" "ababba" "abbba" "abba"
Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".
So, Nastya will remove only three letters.
題目大意:給兩個字符串s1,s2和一個s1長度的數組od[ ],問按od[]給定的順序去掉s1的字母,最多可以去掉多少個字母使s2仍然是s1的子串。
解題思路:本題暴力必定會超時,所以可以對數組進行二分查找。用一個Check函數檢查s1去掉前mid位是否還能使s2是s1的子串,可以則head = mid + 1,否則tail = mid - 1。
代碼:
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cmath> 4 #include<cstring> 5 #include<string> 6 #include<iostream> 7 #include<algorithm> 8 #include<map> 9 #include<stack> 10 #include<queue> 11 using namespace std; 12 typedef long long LL; 13 const LL MaxN = 2e5; 14 15 string s1, s2; 16 int od[MaxN+5], len1, len2; 17 int head, tail, mid, cnt; 18 bool vis[MaxN + 5]; 19 20 int Check(int x) 21 { 22 memset(vis, 0, sizeof(vis)); 23 cnt = 0; 24 for(int i = 0;i <= x;i++) 25 { 26 vis[od[i]-1] = 1; 27 } 28 for(int i = 0;i < len1;i++) 29 { 30 if(vis[i]) continue; 31 if(s1[i] == s2[cnt]) cnt++; 32 if(cnt == len2) return 1; 33 } 34 return 0; 35 } 36 37 int main() 38 { 39 cin >> s1 >> s2; 40 len1 = s1.length();len2 = s2.length(); 41 for(int i = 0;i < len1;i++) 42 { 43 scanf("%d", od + i); 44 } 45 head = 0, tail = len1-1; 46 while(head <= tail) 47 { 48 mid = (head + tail)/2; 49 if(Check(mid)) head = mid + 1; 50 else tail = mid - 1; 51 if(head > tail) 52 { 53 if(tail == mid) printf("%d\n", mid+1); 54 if(head == mid) printf("%d\n", mid); 55 break; 56 } 57 } 58 return 0; 59 }
CodeForces - 779D String Game