Educational Codeforces Round 17 C. Two strings 打表二分
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
hi
bob
-
abca
accepted
ac
abacaba
abcdcba
abcba
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
题意:可以删除b字符串中的一个连续子串,需要你删除留下的最小字符;
思路:首先最开始的思路是n*n*log(n)的,TLE;
枚举b的左端点,二分右端点,check需要O(n);
打表求出从1-i的字符串是a的子串的最小位置,同理求i-n的;
可以优化成n*log(n);
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<iostream> #include<cstdio> #include<cmath> #include<string> #include<queue> #include<algorithm> #include<stack> #include<cstring> #include<vector> #include<list> #include<set> #include<map> using namespace std; #define ll long long #define pi (4*atan(1.0)) #define eps 1e-14 #define bug(x) cout<<"bug"<<x<<endl; const int N=1e5+10,M=1e6+10; const ll INF=1e18+10,mod=2147493647; char a[N],b[N]; int l[N],r[N]; int n,m; int main() { scanf("%s%s",a+1,b+1); n=strlen(a+1),m=strlen(b+1); int st=0; for(int i=1;i<=m;i++) { while(st<=n&&a[st]!=b[i])st++; r[i]=st; if(st<=n)st++; } l[m+1]=n+1; int en=n; for(int i=m;i>=1;i--) { while(en>=1&&a[en]!=b[i])en--; l[i]=en; if(en>=1)en--; } if(r[m]<=n) return 0*printf("%s\n",b+1); int ansl=1,ansr=m; for(int i=1;i<=m;i++) { int st=i; int en=m; int ans=1e6; while(st<=en) { int mid=(st+en)>>1; if(r[i-1]<l[mid+1]) { en=mid-1; ans=mid; } else st=mid+1; } //cout<<ans<<" "<<i<<endl; if(ans-i<ansr-ansl) { ansl=i; ansr=ans; } } if(ansl==1&&ansr==m) printf("-\n"); for(int i=1;i<ansl;i++) printf("%c",b[i]); for(int i=ansr+1;i<=m;i++) printf("%c",b[i]); printf("\n"); return 0; }