import sys k = int(sys.stdin.readline().strip()) for i in range(k): line = sys.stdin.readline().strip().split() alph = line[0] u = line[1] v = line[2] # first, see if either is a substring of the other (including equals): 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. # [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(alph) > 2: print(0) continue # Two-letter alphabet. Make u the longer string: if len(u) < len(v): temp = u u = v v = temp ul = len(u) vl = len(v) # Since we know v is not a substring of u, v must contain include both # letters of the alphabet. [E.g., if v = a^n, then v is not contained in # u b u and we can "pump" strings of the form (ub)^n to get illegal words.] # Then it is sufficient to see whether v is contained in u x u # for each x in alph U {eps} [eps = empty string]. [Proof not hard?] # (If |u|==|v|, also do symmetric check) ok = True # check eps t = u[ul-vl+1:]+u[:vl-1] ok = t.find(v)>= 0 #print(" empty1:",ok) if not ok and ul==vl: # u, v have same length, so symmetric check: t = v[1:]+v[ul-1] ok = t.find(u)>= 0 #print("empty2",ok) for c in alph: if not ok: break t = u[ul-vl+1:]+str(c)+u[:vl-1] ok = t.find(v,0)>= 0 #print("t1 = u[ul-vl+1:]+str(c)+u[:vl-1] =",u[ul-vl+1:],str(c),u[:vl-1]) #print(ok) if not ok and ul==vl: t = v[1:]+str(c)+v[:ul-1] #print("t2 = v[1:]+str(c)+v[:ul-1] =",v[1:],str(c),v[:ul-1]) ok = t.find(u,0) >= 0 #print(ok) if not ok: break if ok: print(1) else: print(0)