#!/usr/bin/python3 """ This implementation is not an intended solution, it is included primarily for verification purposes. It takes advantage of the following properties: 1. For an alphabet of size 2, e.g., {0,1}, x is a subword of every y-bordered word iff x is a subword of each of y000y, y001y, y010y, ..., y111y 2. For an alphabet of size 3, e.g., {0,1,2} or more, x is a subword of every y-bordered word iff x is a subword of y0y, y1y, and y2y. This implies, that such an x must be a subword of y. """ from sys import stdin def main(): line = stdin.readline() num_cases = int(line) for test_case in range(num_cases): tokens = stdin.readline().strip().split(' ') alphabet = tokens[0] bob_word = tokens[1] carol_word = tokens[2] good = False if len(alphabet) == 1: good = True elif len(alphabet) == 2: middles = [f'{i:03b}' for i in range(8)] middles = [ word.replace('0', alphabet[0]).replace('1', alphabet[1]) for word in middles ] carol_between_bobs = True bob_between_carols = True for middle in middles: if carol_word not in bob_word + middle + bob_word: carol_between_bobs = False if bob_word not in carol_word + middle + carol_word: bob_between_carols = False if not carol_between_bobs and not bob_between_carols: break good = carol_between_bobs or bob_between_carols else: if carol_word in bob_word or bob_word in carol_word: good = True else: good = False print(1 if good else 0) if __name__ == '__main__': main()