import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
class Subsequences {
public static void main(String[] args) throws Exception {
int cout = Integer.parseInt(br.readLine());
while(cout-- > 0) {
st = new StringTokenizer(br.readLine());
int cin = Integer.parseInt(st.nextToken());
Subs subs = new Subs(st.nextToken());
while(cin-- > 0) {
String rle = br.readLine();
out.println(subs.subseq(rle) ? "YES" : "NO");
}
}
out.flush();
}
static StringTokenizer st;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
class Subs {
public Subs(String nextToken) {
this.ALPHABET = nextToken;
toArray();
}
public boolean subseq(String rle) {
String[] letter = rle.split("\\d+"), digit = rle.split("[A-Z]");
int n = letter.length,
poz = -1,
t = 0;
for(int i = 1; i < n; i++) {
int c = letter[i].charAt(0) - 65, // litera
l = Integer.parseInt(digit[i - 1]); // ilość wystąpień
if(ar[c] == null || ar[c].size() < l) return false;
///////////////////////////////////////////////////////////////
t = bin(poz + 1, ar[c]) + (l - 1);
if(t >= ar[c].size()) return false;
t = ar[c].get(t);
if(t > poz) {
poz = t;
continue;
}
return false;
}
return true;
}
public static int bin(int key, ArrayList
a) {
int lo = 0;
int hi = a.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2,
cmp = a.get(mid);
if (key < cmp) hi = mid - 1;
else if (key > cmp) lo = mid + 1;
else return mid;
}
return lo == a.size() ? lo - 1 : lo;
}
public void toArray() {
int l = ALPHABET.length();
ar = new ArrayList[26];
for(int i = 0; i < l; i++) {
int c = ALPHABET.charAt(i) - 65;
if(ar[c] == null) ar[c] = new ArrayList();
ar[c].add(i);
}
}
String ALPHABET;
ArrayList[] ar;
}
Wyszukiwarka
Podobne podstrony:
dictionary 1 22
dictionary 20 7
AiSD w4 sortowanie2
dictionary 6 7
dictionary 19 9
dictionary 14 20
dictionary 15 8
dictionary 17 9
więcej podobnych podstron