String opearation
Problem Description
Give you a string S whose length is no more than 1000, and two operations.
Operation 1:read a string Str1,and add to S。S becomes S+str1
Operation 2:read a string Str2,and tell me whether it is a subsequence of S(not necessarily consecutive)
or the subsequence of S',S' equals to S's shifting left("bca"、"cab" all equals to "abc"'s shifting left)
Input
The first line is an integer T(1<=T<=150) ,the number of test cases;
For each test case,
The first line is a string S(length <= 1000)
The second line is a positive integer M (1<=M<=100)
The follow M lines:
Command string (Command is 1 or 2,and the string's length <= 100)
All the strings only consist of lowercase letters
Output
When operation 2 occurs,output "YES" if exists,otherwise "NO"
Sample Input
1 abc 3 1 d 2 dca 2 dbc
Sample Output
NO YES
Hint
Source
Manager
第一次做ACdream的手速赛,这道题虽然不难,但整个解题思路还是挺有意思的,所以就记录下来了。
第一次没看清,以为是要连续的,而且主字符串也是个环,WA了两发。后来发现错误后,很荣欣地AC了。
因为最多只有10000左右的字符,我是记录了每一个字符的位置,用vector记录,然后查找是否是子串时,子串成环,每一种可能都搜一遍,从第一个字符开始搜,每搜一个字符记录这个字符搜到的位置,下一次搜要大于这个位置,至于搜,当然是二分啦。。。
代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#define rep(i,n) for(i=1;i<=n;i++)
#define MM(a,t) memset(a,t,sizeof(a))
#define INF 1e9
typedef long long ll;
#define mod 1000000007
using namespace std;
char st[12000];
char sst[120];
int n,l;
vector<int> ki[30];
void songchi(int ii,int l2){
int i,j;
for(i=ii;i<l2;i++)
{
int index=int(st[i]-'a');
ki[index].push_back(i);
}
}
void fun1(){
int i,j,ii=l;
l+=strlen(sst);
for(i=ii;i<l;i++)
st[i]=sst[i-ii];
songchi(ii,l);
}
int so(int index,int pr){
int l,r,res=-1;
l=0; r=ki[index].size()-1;
while(l<=r){
int mid=(l+r)/2;
if(ki[index][mid]>=pr){
res=ki[index][mid];
r=mid-1;
}
else l=mid+1;
}
if(res==-1) return -1;
else return res;
}
bool fun2(){
int i,j,l2=strlen(sst);
if(l2>l) return false;
if(l2==1){
if(ki[int(sst[0]-'a')].size()!=0) return true;
else return false;
}
for(i=0;i<l2;i++)
{
int s2=i,index=int(sst[i]-'a');
int pr=so(index,0);
if(pr==-1) return false;
else{
s2=(s2+1)%l2;
bool ff=true;
while(s2!=i){
index=int(sst[s2]-'a');
pr=so(index,pr+1);
if(pr==-1){
ff=false;
break;
}
s2=(s2+1)%l2;
}
if(ff) return true;
}
}
return false;
}
int main()
{
int i,j,T;
scanf("%d",&T);
while(T--){
for(i=0;i<26;i++) ki[i].clear();
scanf("%s",&st);
l=strlen(st);
songchi(0,l);
scanf("%d",&n);
rep(i,n){
int op;
scanf("%d",&op);
scanf("%s",&sst);
if(op==1) fun1();
else {
if(fun2()) printf("YES\n");
else printf("NO\n");
}
}
}
return 0;
}