Impartial Strings

시간 제한4초메모리 제한1024 MB

요약
S와 T가 부분 문자열로 나타나는 횟수가 같은 문자열만 생성하는 유한 오토마타를 만들 수 있는지 판정한다.
난이도

어려움10점 중 8점

유형
동적 계획법, 그래프, 문자열 매칭, 구현
정답자
아직 제출이 없습니다

문제

Alice builds machines that generates strings. Alice's machines each consist of NN states, numbered from 11 to NN, and a set of directed edges between these states, each labelled with a character from a fixed set. A subset of the states are "final" states. The machine generates strings by starting at state 11, following a path that terminates at a final state, and concatenating the characters of the edge labels together in the order that the edges are traversed. The path is allowed to visit the same state more than once and can traverse the same edge more than once. The path can pass through final states before eventually terminating at a final state. Self loops are allowed and having two or more edges to and/or from the same state labelled with the same letter is also allowed.

Bob has a favorite string SS. Carol has a favorite string TT. Alice wonders if she can build a machine that can generate exactly the strings that have an equal number of occurrences of SS and TT as substrings. That is, the machine should generate every string that has an equal number of occurrences of SS and TT as substrings and it should not generate any strings that do not satisfy this property. Occurrences may overlap. For example, the string banana has two occurrences of the substring ana. Help Alice determine if it is possible to complete the task for Bob and Carol's favorite strings.

Figure H.1: Example machine for the first case in the sample input.

Figure H.1 gives an example machine for the first case in the sample input. The square states represent the final states.

입력

The first line of input contains a single positive integer KK (1≤K≤50)(1\leq K \leq 50), the number of test cases. This is followed by KK lines each containing three strings AA, SS, TT. The first string, AA, is the fixed set of characters used in the machine. The characters in AA are distinct lowercase english letters. The second string, SS, is Bob's favorite string. The third string, TT, is Carol's favorite string. The lengths of SS and TT satisfy 1≤∣S∣,∣T∣≤5001\leq |S|,|T|\leq 500. It is guaranteed that the distinct characters in SS and TT are a subset of those in AA.

출력

Output one line for each test case. Output 11 if Alice can build a machine as described. Otherwise, output 00.

예제1

  1. 예제 1

    입력
    3
    ab ab ba
    abc ab ba
    cz cczz zzcc
    
    예상 출력
    1
    0
    0