import sys # Let L = all strings with equal numbers of u and v, assume L is regular # Basic idea: if L contains a string with arbitrarily many successive # occurrences of u, the only way to avoid a pumping-lemma-type contradiction # is if two successive occurrences of u always contain an occurrence of v. # We'll need these later: counts number of c's in prefix/suffix def pref(s,c): i = 0 while s[i]==c: i += 1 return i def suff(s,c): i = 0 l = len(s) while s[l-i-1]==c: i += 1 return i # Successive occurrences of u might overlap (e.g., if u = abab then ababab # has two occurrences of u), so "overlap" checks this case: def overlap(u,v): # find all prefixes of u that are also suffixes, then see if v is in two # overlapping copies of u ok = True ul = len(u) # slow prefix check: just look at every prefix for i in range(1,len(u)-1): if u[:i]==u[-i:]: t = u+u[i-ul:] if len(t) < len(v) or t.find(v) < 0: return False return True # "check" calls overlap and also checks for all cases where two occurrences # of u are separated by zero or more characters. def check(sigma,u,v): ok = overlap(u,v) if ok: # If v begins and ends with the same letter, we can always find an x # such that u x u doesn't contain v (e.g., just let x be a sufficiently # long string of 'b's if v begins and ends with 'a'). if v[0] == v[-1]: return False # If v is of the form "a^m b" and uu contains v (and variations) if v[0]==sigma[0]: m = pref(v,sigma[0]) n = suff(v,sigma[1]) else: m = suff(v,sigma[0]) n = pref(v,sigma[1]) # at least one of m, n must be 1: if m!=1 and n!= 1: return False ok = (u+u).find(v)>= 0 return ok ####################################### # main: k = int(sys.stdin.readline().strip()) for i in range(k): line = sys.stdin.readline().strip().split() sigma = line[0] u = line[1] v = line[2] # first, see if either is a substring of the other (including equals). # If so, trivial: if u.find(v)>= 0 or v.find(u) >= 0: print(1) continue # We know that neither of u,v is a substring of the other. # If there are more than 2 letters in the alphabet, not regular. # [REASON: Suppose alphabet = {a,b,c}, suppose that c is neither the first # nor the last letter of v. Then it's not hard to show that, for # suffiently large n, "u c^n u" does not contain v.] if len(sigma) > 2: print(0) continue # Two-letter alphabet. Make u the longer string: if len(u) < len(v): temp = u u = v v = temp ok = check(sigma,u,v) if ok: print(1) else: print(0)