Problem: 2050E - Three Strings
Language: java

Solution 1 (runtime: 171 ms):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;

public class q1 {
    static int MOD = (int) (1e9 + 7);
    static int INF = Integer.MIN_VALUE;
    static int INT_MAX = Integer.MAX_VALUE;

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        char nextChar() {
            return next().charAt(0);
        }

        String nextLine() {
            String str = "";
            try {
                if (st.hasMoreTokens()) {
                    str = st.nextToken("\n");
                } else {
                    str = br.readLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    static long gcd(long a, long b) {
        return b == 0 ? a : gcd(b, a % b);
    }
    // Usage: Find the greatest common divisor of two numbers.
    // Time Complexity: O(log(min(a, b)))
    // Space Complexity: O(log(min(a, b))) [recursive stack]

    static long lcm(long a, long b) {
        return (a / gcd(a, b)) * b;
    }
    // Usage: Find the least common multiple of two numbers.
    // Time Complexity: O(log(min(a, b)))
    // Space Complexity: O(log(min(a, b))) [recursive stack]

    static long power(long a, long b, long m) {
        long res = 1;
        a %= m;
        while (b > 0) {
            if ((b & 1) == 1)
                res = (res * a) % m;
            a = (a * a) % m;
            b >>= 1;
        }
        return res;
    }
    // Usage: Calculate (a^b) % m efficiently.
    // Time Complexity: O(log(b))
    // Space Complexity: O(1)

    static long modInverse(long a, long m) {
        return power(a, m - 2, m); // Fermat's Little Theorem
    }

    // ETF(Euler Totient function) ϕ(n).
    // find all unique prime factors of n
    // then do the below job.
    // Time Complexity:O(root N)
    // Space Complexity:O(1)
    static int phi(int n) {
        int result = n; // Start with n
        for (int p = 2; p * p <= n; p++) {
            // Check if p is a prime factor of n
            if (n % p == 0) {
                // If p is a factor, divide n by p repeatedly
                while (n % p == 0) {
                    n /= p;
                }
                // Apply the formula
                result -= result / p;
            }
        }
        // If n is still greater than 1, it must be a prime factor
        if (n > 1) {
            result -= result / n;
        }
        return result;
    }
    // Euler's theorm
    // a^ϕ(n)≡1 (mod n)
    // (a^b)%m≡(a^(b%ϕ(m)))%m :given a and m are co-prime(gcd(a,m)=1)

    // justsmall->largest index i such that arr[i] ≤ x.
    // justgreat->smallest index i such that arr[i] >=x.
    // time complexity:O(log(n))
    static int binarySearch(long[] arr, long x, boolean findJustSmall, boolean findJustGreat) {
        int left = 0, right = arr.length - 1, result = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == x) {
                if (!findJustSmall && !findJustGreat)
                    return mid; // Exact match
                // Continue for justSmall/justGreat logic
            }

            if (findJustSmall) {
                if (arr[mid] <= x) {
                    result = mid; // Last valid index where arr[mid] <= x
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            } else if (findJustGreat) {
                if (arr[mid] >= x) {
                    result = mid; // First valid index where arr[mid] >= x
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                if (arr[mid] < x) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }

        return result;
    }

    // Sieve of Eratosthenes
    // Usage: Find all prime numbers up to n using the sieve of Eratosthenes.
    // Time Complexity: O(n log log n)
    // Space Complexity: O(n)
    static boolean[] primeSieve(int n) {
        boolean[] isPrime = new boolean[n + 1];
        Arrays.fill(isPrime, true);
        isPrime[0] = isPrime[1] = false;
        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                for (int j = i * i; j <= n; j += i) {
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }

    static boolean isPrimeSquare(long n, boolean[] isPrime) {
        if (n < 4)
            return false; // Smallest prime square is 2^2 = 4

        long s = (long) Math.sqrt(n);
        if (s * s != n)
            return false; // Check if n is a perfect square
        if (s > isPrime.length - 1)
            return false; // Ensure s is within precomputed range
        return isPrime[(int) s]; // Check if sqrt(n) is a prime
    }

    // Usage: Precompute cumulative sums for quick subarray sum queries
    // Time Complexity: O(n), where n is the size of the array
    // Space Complexity: O(n) for the prefix array
    static long[] prefixSum(long[] arr) {
        long[] prefix = new long[arr.length + 1];
        for (int i = 1; i <= arr.length; i++) {
            prefix[i] = prefix[i - 1] + arr[i - 1];
        }
        return prefix;
    }

    // Usage: Precompute cumulative sums for 2D matrices to quickly find the sum of
    // any submatrix
    // Time Complexity: O(n * m), where n is the number of rows and m is the number
    // of columns
    // Space Complexity: O(n * m) for the prefix array
    static long[][] prefixSum2D(long[][] matrix) {
        int n = matrix.length, m = matrix[0].length;
        long[][] prefix = new long[n + 1][m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                prefix[i][j] = matrix[i - 1][j - 1]
                        + prefix[i - 1][j]
                        + prefix[i][j - 1]
                        - prefix[i - 1][j - 1];
            }
        }
        return prefix;
    }

    static long[] factorial;
    static long[] inverseFactorial;
    static void precomputeFactorials(int n, int mod) {
        factorial = new long[n + 1];
        inverseFactorial = new long[n + 1];
        factorial[0] = inverseFactorial[0] = 1;
        for (int i = 1; i <= n; i++) {
            factorial[i] = factorial[i - 1] * i % mod;
        }
        inverseFactorial[n] = power(factorial[n], mod - 2, mod);
        for (int i = n - 1; i >= 1; i--) {
            inverseFactorial[i] = inverseFactorial[i + 1] * (i + 1) % mod;
        }
    }
    static long nCr(int n, int r, int mod) {
        if (r > n || n < 0 || r < 0)
            return 0;
        return factorial[n] * inverseFactorial[r] % mod * inverseFactorial[n - r] % mod;
    }
    // Usage: Calculate nCr % mod (combination formula).
    // Precompute factorials using precomputeFactorials().
    // Time Complexity: O(log(mod)) per query (after precomputation).
    // Space Complexity: O(n) for factorial arrays.

    static long maxSubarraySum(long[] arr, int k) {
        long maxSum = Long.MIN_VALUE, windowSum = 0;
        for (int i = 0; i < arr.length; i++) {
            windowSum += arr[i];
            if (i >= k - 1) {
                maxSum = Math.max(maxSum, windowSum);
                windowSum -= arr[i - (k - 1)];
            }
        }
        return maxSum;
    }
    // Usage: Find the maximum sum of any subarray of size k.
    // Time Complexity: O(n)
    // Space Complexity: O(1)

    static int longestSubarrayWithSumAtMostK(int[] arr, int k) {
        int left = 0, sum = 0, maxLength = 0;
        for (int right = 0; right < arr.length; right++) {
            sum += arr[right];
            while (sum > k) {
                sum -= arr[left++];
            }
            maxLength = Math.max(maxLength, right - left + 1);
        }
        return maxLength;
    }
    // Usage: Find the length of the longest subarray with sum at most k.
    // Time Complexity: O(n)
    // Space Complexity: O(1)

    // Fenwick Tree (BIT)
    // Usage: Efficiently handle range sum queries and point updates
    // Time Complexity: O(log n) for both update and query operations
    // Space Complexity: O(n), where n is the size of the Fenwick tree
    static class FenwickTree {
        private long[] tree;

        FenwickTree(int n) {
            tree = new long[n + 1];
        }

        void update(int index, long value) {
            while (index < tree.length) {
                tree[index] += value;
                index += index & -index;
            }
        }

        long query(int index) {
            long sum = 0;
            while (index > 0) {
                sum += tree[index];
                index -= index & -index;
            }
            return sum;
        }

        long rangeQuery(int left, int right) {
            return query(right) - query(left - 1);
        }
    }

    // Segment Tree (Range Queries)
    // Usage: Handle range queries (sum, min, max) and point updates efficiently
    // Time Complexity: O(n) for construction, O(log n) for queries and updates
    // Space Complexity: O(n) for the input array and O(4 * n) for the segment tree
    static class SegmentTree {
        private long[] tree, arr;
        private int n;

        SegmentTree(long[] input) {
            n = input.length;
            arr = Arrays.copyOf(input, n);
            tree = new long[4 * n];
            build(0, 0, n - 1);
        }

        private void build(int node, int start, int end) {
            if (start == end) {
                tree[node] = arr[start];
            } else {
                int mid = (start + end) / 2;
                build(2 * node + 1, start, mid);
                build(2 * node + 2, mid + 1, end);
                tree[node] = merge(tree[2 * node + 1], tree[2 * node + 2]);
            }
        }

        private long merge(long left, long right) {
            return Math.min(left, right); // Replace with logic (min, max, sum)
        }

        public void update(int index, long value) {
            update(0, 0, n - 1, index, value);
        }

        private void update(int node, int start, int end, int index, long value) {
            if (start == end) {
                tree[node] = value;
            } else {
                int mid = (start + end) / 2;
                if (index <= mid) {
                    update(2 * node + 1, start, mid, index, value);
                } else {
                    update(2 * node + 2, mid + 1, end, index, value);
                }
                tree[node] = merge(tree[2 * node + 1], tree[2 * node + 2]);
            }
        }

        public long query(int left, int right) {
            return query(0, 0, n - 1, left, right);
        }

        private long query(int node, int start, int end, int left, int right) {
            if (start > right || end < left)
                return INF;
            if (start >= left && end <= right)
                return tree[node];
            int mid = (start + end) / 2;
            long lQuery = query(2 * node + 1, start, mid, left, right);
            long rQuery = query(2 * node + 2, mid + 1, end, left, right);
            return merge(lQuery, rQuery);
        }
    }


//implementation of Trie data structure
//L-length of the word in each function
//n->number of words inserted
//T.c->O(L) for all functions
//S.c->O(n*L*26) for all functions
    class Trie {
        // TrieNode class to represent each node in the Trie
         class TrieNode {
            TrieNode[] children;
            boolean isEndOfWord;
    
            public TrieNode() {
                children = new TrieNode[26]; // Supports only lowercase 'a' to 'z'
                isEndOfWord = false;
            }
        }
    
        private TrieNode root;
    
        // Constructor
        public Trie() {
            root = new TrieNode();
        }
    
        // Insert a word into the Trie
        public void insert(String word) {
            TrieNode node = root;
            for (char ch : word.toCharArray()) {
                int index = ch - 'a'; // Map 'a' to 0, 'z' to 25
                if (node.children[index] == null) {
                    node.children[index] = new TrieNode();
                }
                node = node.children[index];
            }
            node.isEndOfWord = true;
        }
    
        // Check if a word exists in the Trie
        public boolean search(String word) {
            TrieNode node = root;
            for (char ch : word.toCharArray()) {
                int index = ch - 'a';
                if (node.children[index] == null) {
                    return false;
                }
                node = node.children[index];
            }
            return node.isEndOfWord;
        }
    
        // Check if a prefix exists in the Trie
        public boolean startsWith(String prefix) {
            TrieNode node = root;
            for (char ch : prefix.toCharArray()) {
                int index = ch - 'a';
                if (node.children[index] == null) {
                    return false;
                }
                node = node.children[index];
            }
            return true;
        }
    }
    




     // T.C. = O(n) -> We traverse the array once.
    // S.C. = O(1) -> We use only a few variables.
    static int maxSubarraySum(int[] arr) {
        int maxSoFar = arr[0]; // Maximum sum found so far
        int currentMax = arr[0]; // Maximum sum ending at the current position

        for (int i = 1; i < arr.length; i++) {
            currentMax = Math.max(arr[i], currentMax + arr[i]); // Include or reset
            maxSoFar = Math.max(maxSoFar, currentMax); // Update max
        }

        return maxSoFar;
    }

    // 2-d kadane
    // T.C. = O(n^3) -> Outer loop (O(n)) for top row,
    // Inner loop (O(n)) for bottom row,
    // Applying 1D Kadane (O(n)) on each row combination.
    // S.C. = O(n) -> Space used by the temp array for column sums.
    static int maxSubmatrixSum(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int maxSum = Integer.MIN_VALUE;

        // Iterate over all possible top rows
        for (int top = 0; top < rows; top++) {
            int[] temp = new int[cols]; // Temporary array for column sums

            // Sum over all rows from `top` to `bottom`
            for (int bottom = top; bottom < rows; bottom++) {
                for (int col = 0; col < cols; col++) {
                    temp[col] += matrix[bottom][col];
                }

                // Apply 1D Kadane's on the column sums array
                int currentMax = maxSubarraySum(temp);
                maxSum = Math.max(maxSum, currentMax); // Update global max
            }
        }

        return maxSum;
    }

    // Graph Algorithms
    // Usage: Compute shortest paths between all pairs of nodes in a graph
    // Time Complexity: O(n^3), where n is the number of nodes
    // Space Complexity: O(n^2) for the distance matrix
    static void floydWarshall(long[][] dist) {
        int n = dist.length;
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
                }
            }
        }
    }
    //prim's algo 
    //O(ElogV)
    static int primMST(int n, List<List<Edge1>> adj) {
        boolean[] visited = new boolean[n];
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); // {node, weight}
        pq.add(new int[]{0, 0}); // Start with node 0
        int mstCost = 0;

        while (!pq.isEmpty()) {
            int[] current = pq.poll();
            int node = current[0], weight = current[1];
            if (visited[node]) continue;

            visited[node] = true;
            mstCost += weight;

            for (Edge1 neighbor : adj.get(node)) {
                if (!visited[neighbor.node]) {
                    pq.add(new int[]{neighbor.node, neighbor.weight});
                }
            }
        }

        return mstCost;
    }


    //kruskal algorithm
    //O(ElogV)
    static int kruskalMST(int n, List<Edge> edges) {
        // Sort edges by weight
        edges.sort((a, b) -> a.weight - b.weight);

        int[] parent = new int[n];
        int[] rank = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;

        int mstCost = 0;
        int edgeCount = 0;

        for (Edge edge : edges) {
            if (find(parent, edge.src) != find(parent, edge.dest)) {
                mstCost += edge.weight;
                union(parent, rank, edge.src, edge.dest);
                edgeCount++;
                if (edgeCount == n - 1) break;
            }
        }

        return mstCost;
    }
    static int find(int[] parent, int x) {
        if (parent[x] != x) {
            parent[x] = find(parent, parent[x]); // Path compression
        }
        return parent[x];
    }
    static void union(int[] parent, int[] rank, int x, int y) {
        int rootX = find(parent, x);
        int rootY = find(parent, y);
    
        if (rootX != rootY) {
            if (rank[rootX] > rank[rootY]) {
                parent[rootY] = rootX; // Attach smaller tree under larger tree
            } else if (rank[rootX] < rank[rootY]) {
                parent[rootX] = rootY;
            } else {
                parent[rootY] = rootX;
                rank[rootX]++; // Increase rank only if they were equal
            }
        }
    }
        




   

    // Usage: Find shortest paths from a start node to all other nodes in a weighted
    // graph
    // Time Complexity: O((n + e) log n), where n is the number of nodes and e is
    // the number of edges
    // Space Complexity: O(n + e) for the graph representation
    static long[] dijkstra(int start, ArrayList<int[]>[] graph, int n) {
        long[] dist = new long[n];
        Arrays.fill(dist, INF);
        dist[start] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[1]));
        pq.add(new int[] { start, 0 });

        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int node = curr[0];
            long d = curr[1];
            if (d > dist[node])
                continue;

            for (int[] edge : graph[node]) {
                int next = edge[0], weight = edge[1];
                if (dist[node] + weight < dist[next]) {
                    dist[next] = dist[node] + weight;
                    pq.add(new int[] { next, (int) dist[next] });
                }
            }
        }
        return dist;
    }
    //like dijkstra
    //o(v*e)
    static int[] bellmanFord(int vertices, int edges, List<Edge> edgeList, int source) {
        int[] distance = new int[vertices];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[source] = 0;
        for (int i = 1; i < vertices; i++) {
            for (Edge edge : edgeList) {
                if (distance[edge.src] != Integer.MAX_VALUE && distance[edge.src] + edge.weight < distance[edge.dest]) {
                    distance[edge.dest] = distance[edge.src] + edge.weight;
                }
            }
        }
        for (Edge edge : edgeList) {
            if (distance[edge.src] != Integer.MAX_VALUE && distance[edge.src] + edge.weight < distance[edge.dest]) {
                return null; 
            }
        }
        return distance; 
    }


    //bipartite check
    static boolean isBipartite(int vertices, List<List<Integer>> graph) {
        int[] colors = new int[vertices];
        Arrays.fill(colors, -1); // -1 indicates unvisited nodes

        // Iterate over all components of the graph
        for (int i = 0; i < vertices; i++) {
            if (colors[i] == -1) { // Unvisited node
                if (!bfsCheck(i, graph, colors)) {
                    return false;
                }
            }
        }
        return true;
    }

    private static boolean bfsCheck(int start, List<List<Integer>> graph, int[] colors) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);
        colors[start] = 0; // Start with color 0

        while (!queue.isEmpty()) {
            int node = queue.poll();
            for (int neighbor : graph.get(node)) {
                if (colors[neighbor] == -1) {
                    // Assign the opposite color to the neighbor
                    colors[neighbor] = 1 - colors[node];
                    queue.add(neighbor);
                } else if (colors[neighbor] == colors[node]) {
                    // If the neighbor has the same color, it's not bipartite
                    return false;
                }
            }
        }
        return true;
    }
    

    // -------------------- KMP Algorithm --------------------
    // Usage: Precompute LPS array for efficient pattern matching in strings
    // Time Complexity: O(n), where n is the length of the pattern
    // Space Complexity: O(n) for the LPS array
    static int[] kmp(String pattern) {
        int n = pattern.length();
        int[] lps = new int[n];
        int len = 0, i = 1;
        while (i < n) {
            if (pattern.charAt(i) == pattern.charAt(len)) {
                lps[i++] = ++len;
            } else if (len > 0) {
                len = lps[len - 1];
            } else {
                lps[i++] = 0;
            }
        }
        return lps;
    }

    // Usage: Find all occurrences of a pattern in a text using the KMP algorithm
    // Time Complexity: O(n + m), where n is the length of the text and m is the
    // length of the pattern
    // Space Complexity: O(m) for the LPS array
    static List<Integer> kmpSearch(String text, String pattern) {
        int[] lps = kmp(pattern);
        List<Integer> result = new ArrayList<>();
        int i = 0, j = 0;
        while (i < text.length()) {
            if (text.charAt(i) == pattern.charAt(j)) {
                i++;
                j++;
            }
            if (j == pattern.length()) {
                result.add(i - j);
                j = lps[j - 1];
            } else if (i < text.length() && text.charAt(i) != pattern.charAt(j)) {
                if (j > 0) {
                    j = lps[j - 1];
                } else {
                    i++;
                }
            }
        }
        return result;
    }

    // -------------------- Rabin-Karp Algorithm --------------------
    // Usage: Find all occurrences of a pattern in a text using Rabin-Karp algorithm
    // Time Complexity: O(n + m) on average, O(n * m) in worst case due to hash
    // collisions
    // Space Complexity: O(1) additional space for rolling hash
    private final static int prime = 31;

    static int patternSearch(char[] text, char[] pattern) {
        int m = pattern.length;
        int n = text.length;

        long patternHash = createHash(pattern, m - 1);
        long textHash = createHash(text, m - 1);

        for (int i = 1; i <= n - m + 1; i++) {
            if (patternHash == textHash && checkEqual(text, i - 1, i + m - 2, pattern, 0, m - 1)) {
                return i - 1;
            }
            if (i < n - m + 1) {
                textHash = recalculateHash(text, i - 1, i + m - 1, textHash, m);
            }
        }

        return -1;
    }

    static long recalculateHash(char[] str, int oldIndex, int newIndex, long oldHash, int patternLen) {
        long newHash = oldHash - str[oldIndex];
        newHash /= prime; // Adjust the hash for the next window
        newHash += str[newIndex] * Math.pow(prime, patternLen - 1); // Add new character to hash
        return newHash;
    }

    static long createHash(char[] str, int end) {
        long hash = 0;
        for (int i = 0; i <= end; i++) {
            hash += str[i] * Math.pow(prime, i); // Calculate hash using powers of prime
        }
        return hash;
    }

    static boolean checkEqual(char[] str1, int start1, int end1, char[] str2, int start2, int end2) {
        if (end1 - start1 != end2 - start2) {
            return false;
        }
        while (start1 <= end1 && start2 <= end2) {
            if (str1[start1] != str2[start2]) {
                return false;
            }
            start1++;
            start2++;
        }
        return true;
    }

    // -------------------- Z-Algorithm --------------------
    // Usage: Precompute Z array for efficient pattern matching in strings
    // Time Complexity: O(n), where n is the length of the combined string
    // Space Complexity: O(n) for the Z array
    static int[] zAlgorithm(String s) {
        int n = s.length();
        int[] z = new int[n];
        int l = 0, r = 0;
        for (int i = 1; i < n; i++) {
            if (i <= r) {
                z[i] = Math.min(r - i + 1, z[i - l]);
            }
            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) {
                z[i]++;
            }
            if (i + z[i] - 1 > r) {
                l = i;
                r = i + z[i] - 1;
            }
        }
        return z;
    }

    // Usage: Find all occurrences of a pattern in a text using Z-Algorithm
    // Time Complexity: O(n + m), where n is the length of the text and m is the
    // length of the pattern
    // Space Complexity: O(n + m) for the concatenated string and Z array
    static List<Integer> zSearch(String text, String pattern) {
        String combined = pattern + "$" + text; // "$" acts as a separator
        int[] z = zAlgorithm(combined);
        List<Integer> result = new ArrayList<>();
        for (int i = pattern.length() + 1; i < combined.length(); i++) {
            if (z[i] == pattern.length()) {
                result.add(i - pattern.length() - 1);
            }
        }
        return result;
    }
    //O(n) for finding next greater element of every element of array
     static int[] nextGreater(int[] arr) {
        int n = arr.length;
        int[] result = new int[n];
        Stack<Integer> stack = new Stack<>();
        for (int i = n - 1; i >= 0; i--) {
            while (!stack.isEmpty() && stack.peek() <= arr[i]) {
                stack.pop();
            }
            result[i] = stack.isEmpty() ? -1 : stack.peek();
            stack.push(arr[i]);
        }
        return result;
    }
   //O(n) for finding next smaller element of every element of array
    static int[] nextSmaller(int[] arr) {
        int n = arr.length;
        int[] result = new int[n];
        Stack<Integer> stack = new Stack<>();

        for (int i = n - 1; i >= 0; i--) {
            while (!stack.isEmpty() && stack.peek() >= arr[i]) {
                stack.pop();
            }
            result[i] = stack.isEmpty() ? -1 : stack.peek();
            stack.push(arr[i]);
        }

        return result;
    }



//sparse table for static arrays for handling range
//T.c->O(nlogn)[for creating table]
//range query->O(1)
class SparseTable {
    private int[][] st; // Sparse table
    private int[] log;  // Logarithm values
    private int n;      // Array size

    // Constructor: Build the Sparse Table
    public SparseTable(int[] arr) {
        this.n = arr.length;
        int maxLog = (int) (Math.log(n) / Math.log(2)) + 1;

        // Initialize Sparse Table and log array
        st = new int[n][maxLog];
        log = new int[n + 1];

        // Compute log values for fast access
        for (int i = 2; i <= n; i++) {
            log[i] = log[i / 2] + 1;
        }

        // Fill the first column of Sparse Table
        for (int i = 0; i < n; i++) {
            st[i][0] = arr[i];
        }

        // Fill the rest of the Sparse Table
        for (int j = 1; (1 << j) <= n; j++) {
            for (int i = 0; i + (1 << j) - 1 < n; i++) {
                st[i][j] = Math.min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);//this line is changed for handling different problem 
            }
        }
    }
    public int query(int L, int R) {
        int j = log[R - L + 1];
        return Math.min(st[L][j], st[R - (1 << j) + 1][j]);//this line is changed for handling different problem 
                                   //L+(R-L+1)-2^j
    }
}




    // modulo factorial
    static long fact(long n) {
        long ans = 1;
        long m = (long) (1e9 + 7);
        for (long i = 1; i <= n; i++)
            ans = (ans * i) % m;
        return ans;
    }
    static int inversions(char[] s1, char[] s2, char[] s) {
        int n = s1.length, m = s2.length;
        int[][] dp = new int[n + 1][m + 1];
        for (int[] row : dp) {
            Arrays.fill(row, Integer.MAX_VALUE);
        }
        dp[0][0] = 0;
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                int k = i + j;
                if (k >= s.length) continue;
                if (i < n && s[k] == s1[i]) {
                    dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j]);
                }
                if (j < m && s[k] == s2[j]) {
                    dp[i][j + 1] = Math.min(dp[i][j + 1], dp[i][j]);
                }
                if (i < n) {
                    dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + 1);
                }
                if (j < m) {
                    dp[i][j + 1] = Math.min(dp[i][j + 1], dp[i][j] + 1);
                }
            }
        }

        return dp[n][m];
    }


    public static void main(String[] args) throws IOException {
        OutputStream outputStream = System.out;
        PrintWriter out = new PrintWriter(outputStream);
        FastReader sc = new FastReader();
        int totalTests = sc.nextInt();
        while (totalTests-- > 0) {
char s1[]=sc.next().toCharArray();
char s2[]=sc.next().toCharArray();
char s[]=sc.next().toCharArray();
System.out.println(inversions(s1,s2,s));



















    }
    }
}

class Pair<F, S> {
    F first;
    S second;

    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }
}

class Triplet<F, S, T> {
    F first;
    S second;
    T third;

    public Triplet(F first, S second, T third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }
}

class Edge {
    public int src;
    public int dest;
    public int weight;

    public Edge(int src, int dest, int weight) {
        this.src = src;
        this.dest = dest;
        this.weight = weight;
    }
}
class Edge1 {
    int node, weight;

    Edge1(int node, int weight) {
        this.node = node;
        this.weight = weight;
    }
}


Solution 2 (runtime: 202 ms):
import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintStream;

import java.util.*;



public class Main {



    static int mod = 998__244______________________________________________________353;



    static int inf = (int) 2e9;



    static long infL = (long) 9e18;

    private static final int N = (int) (2e5+10);

    static int []f = new int[N];

    static int []las = new int[N];

    static int []pre = new int[N];



    static int []log = new int[N];





    static Pair<Integer,Integer> []pair = new Pair[N];

    static int n,k;



    static int[] dx = new int[]{-1,1,0,0};

    static int[] dy = new int[]{0,0,-1,1};

    static int [][] dp = new int[2025][2025];

    private static void solve(){

        String a = inStr(),b = inStr(),c = inStr();

        dp[0][0] = 0;

        for(int i=0;i<=a.length();i++){

            for(int j=0;j<=b.length();j++){

                int res = inf;

                if(i + j ==0)continue;

                if(i != 0){

                    res = Math.min(res,dp[i-1][j] + (a.charAt(i-1) == c.charAt(i + j-1)? 0 : 1));//决策a[i-1] 这个位置

                }

                if(j != 0){

                    res = Math.min(res,dp[i][j-1] + (b.charAt(j-1) == c.charAt(i + j-1)? 0 : 1));

                }

                dp[i][j] = res;

            }

        }

        println(dp[a.length()][b.length()]);

    }





    public static void main(String[] args) {

        for(int i=2;i<N;i++){

            log[i] = log[i/2] + 1;

        }

        int t = 1;

        t = in();

        while (t-- > 0) {

            solve();

        }

    }





    private static class GcdST{



        private static final int[][] st = new int[35][200020];





        public void init(int[] f,int n){

//            for(int k=0;k<=log[n]+1;k++){

//                for(int i=1;i + (1<<k) - 1 <=n ;i++){

//                    if(k==0)st[i][k] = f[i];

//                    else {

//                        st[i][k] = gcd(st[i][k-1],st[i+(1<<(k-1))][k-1]);

//                    }

//                }

//            }

            for(int k=0;k<=log[n]+1;k++){

                for(int i=1;i + (1<<k) - 1 <=n ;i++){

                    if(k==0)st[k][i] = f[i];

                    else {

                        st[k][i] = gcd(st[k-1][i],st[k-1][i+(1<<(k-1))]);

                    }

                }

            }



        }



        public int get(int l,int r){

            if(l==r){

                return st[0][l];

            }

            int x = r - l + 1;

            int res = gcd(st[log[x]][l],st[log[x]][r - (1<<log[x]) + 1]);

//            int res = 0,c = 0,base = 1;

//            while(x > 0){

//                if((x & 1) == 1){

//                    res = gcd(res,st[l][c]);

//                    l += base; // x x x x

//                }

//                x /= 2;

//                c++;

//                base *= 2;

//            }

//            for (int k = 25;k>=0;k--){

//                if(((x >> k) & 1) == 1){

//                    res = gcd(res,st[l][k]);

//                    l += 1<<k; // x x x x

//                }

//            }

            return res;

        }







    }





    private static class SegTree{



        private static class Node{

            int l,r;

            long max,min;

        }

        final Node []tr;

        public SegTree(int n){

            tr = new Node[n << 2];

            for (int i = 0; i < tr.length; i++) {

                tr[i] = new Node(); // 初始化所有节点

            }

        }

        public void init(int idx,int l,int r){

            tr[idx].l = l;

            tr[idx].r = r;

            if (l == r) { // 叶节点

                tr[idx].max = -inf;

                tr[idx].min = inf;

                return;

            }

            int mid = (l + r) >> 1;

            init(idx * 2, l, mid ); // 左子树

            init(idx * 2 + 1, mid + 1, r); // 右子树

            pushUp(idx); // 合并子树信息

        }

        // 合并子节点信息

        private void pushUp(int idx) {

            tr[idx].max = Math.max(tr[idx * 2].max, tr[idx * 2 + 1].max);

            tr[idx].min = Math.min(tr[idx * 2].min, tr[idx * 2 + 1].min);

        }





        // 区间查询最大值和最小值

        public long[] query(int l, int r, int idx) {

            if (tr[idx].l >= l && tr[idx].r <= r) { // 当前节点区间完全包含在查询区间中

                return new long[]{tr[idx].max, tr[idx].min};

            }

            int mid = (tr[idx].l + tr[idx].r) >> 1;

            long maxVal = Long.MIN_VALUE;

            long minVal = Long.MAX_VALUE;

            if (l <= mid) { // 查询左子树

                long[] leftRes = query(l, r, idx * 2);

                maxVal = leftRes[0];

                minVal = leftRes[1];

            }

            if (r > mid) { // 查询右子树

                long[] rightRes = query(l, r, idx * 2 + 1);

                maxVal = Math.max(maxVal, rightRes[0]);

                minVal = Math.min(minVal, rightRes[1]);

            }

            return new long[]{maxVal, minVal};

        }



        // 单点更新

        public void update(int idx, int pos, int value) {

            if (tr[idx].l == tr[idx].r) { // 找到目标叶节点

                tr[idx].max = tr[idx].min = value;

                return;

            }

            int mid = (tr[idx].l + tr[idx].r) >> 1;

            if (pos <= mid) { // 更新左子树

                update(idx * 2,pos, value);

            } else { // 更新右子树

                update(idx * 2 + 1,pos, value);

            }

            pushUp(idx); // 更新当前节点

        }



    }



    //  -===-      MATH       -===-  //



    static int fact(int n) {

        int r = 1;

        for (int i = 1; i <= n; i++) {

            r = (int) (((long) r * i) % mod);

        }

        return r;

    }



    static int C(int n, int k) {

        return (int) (((((long) fact(n) * pow(fact(k), mod - 2)) % mod) * pow(fact(n - k), mod - 2)) % mod);

    }



    static int gcd(int i1, int i2) {

        if (i2 == 0) return i1;

        return gcd(i2, i1 % i2);

    }



    static long gcd(long i1, long i2) {

        if (i2 == 0) return i1;

        return gcd(i2, i1 % i2);

    }



    static int pow(int x, int y) {

        x = x % mod;

        if (x == 0) return 0;

        int r = 1;

        while (y > 0) {

            if ((y & 1) != 0) r = (int) (((long) r * x) % mod);

            y /= 2;

            x = (int) (((long) x * x) % mod);

        }

        return r % mod;

    }



    static void swap(int[] a, int i, int j) {

        int tmp = a[i];

        a[i] = a[j];

        a[j] = tmp;

    }



    static int digitSum(long n) {

        int r = 0;

        while (n != 0) {

            r += (int) (n % 10);

            n /= 10;

        }

        return r;

    }



    //  -===- DATA STRUCTURES -===-  //



    static class UnionFind {



        int[] p, rank, min, max, sz;

        int n, c;



        UnionFind(int n) {

            this.n = n;

            p = new int[n];

            rank = new int[n];

            min = new int[n];

            max = new int[n];

            sz = new int[n];

            for (int i = 0; i < p.length; i++) {

                p[i] = i;

                min[i] = i;

                max[i] = i;

                sz[i] = 1;

            }

        }



        int find(int a) {

            return p[a] = (p[a] == a ? a : find(p[a]));

        }



        void union(int a, int b) {

            a = find(a);

            b = find(b);

            if (a == b) return;

            if (rank[a] > rank[b]) {

                p[b] = a;

                max[a] = Math.max(max[a], max[b]);

                min[a] = Math.min(min[a], min[b]);

                sz[a] += sz[b];

            } else {

                p[a] = b;

                max[b] = Math.max(max[b], max[a]);

                min[b] = Math.min(min[b], min[a]);

                sz[b] += sz[a];

                if (rank[a] == rank[b]) {

                    rank[b]++;

                }

            }

            c--;

        }

    }



    private static class Pair<F, S> {



        int index;



        F first;

        S second;



        public Pair(F f, S s) {

            this.first = f;

            this.second = s;

        }



        public F getFirst() {

            return first;

        }



        public S getSecond() {

            return second;

        }



        public void setFirst(F first) {

            this.first = first;

        }



        public void setSecond(S second) {

            this.second = second;

        }



        public int getIndex() {

            return index;

        }



        public void setIndex(Integer index) {

            this.index = index;

        }



        @Override

        public String toString(){

            return first.toString() + ',' + second.toString();

        }



    }





    //  -===-      IN      -===-  //

    static StringTokenizer STT;



    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));



    static PrintStream out = System.out;



    static String inStr() {

        while (STT == null || !STT.hasMoreElements()) {

            try {

                STT = new StringTokenizer(br.readLine());

            } catch (IOException e) {

                throw new RuntimeException(e);

            }

        }

        return STT.nextToken();

    }



    static int in() {

        return Integer.parseInt(inStr());

    }



    static long inLong() {

        return Long.parseLong(inStr());

    }



    static double inDouble() {

        return Double.parseDouble(inStr());

    }



    static String inLine() {

        String s;

        try {

            if (STT != null && STT.hasMoreTokens()) {

                s = STT.nextToken("\n");

            } else {

                s = br.readLine();

            }

        } catch (IOException e) {

            throw new RuntimeException(e);

        }

        return s;

    }



    static long[] inArrLong() {

        String[] split = inLine().split(" ");

        long[] a = new long[split.length];

        for (int i = 0; i < a.length; i++) {

            a[i] = Long.parseLong(split[i]);

        }

        return a;

    }



    static int[] inArr() {

        String s = inLine();

        String[] split = s.split(" ");

        int[] a = new int[split.length];

        for (int i = 0; i < a.length; i++) {

            a[i] = Integer.parseInt(split[i]);

        }

        return a;

    }



    //  -===-      PRINT      -===-  //



    static void YES() {

        out.println("YES");

    }



    static void NO() {

        out.println("NO");

    }



    static void println() {

        out.println();

    }



    static void println(int a) {

        out.println(a);

    }



    static void print(int a) {

        out.print(a);

    }



    static void println(long a) {

        out.println(a);

    }



    static void print(long a) {

        out.print(a);

    }



    static void println(double a) {

        out.println(a);

    }



    static void print(double a) {

        out.print(a);

    }



    static void println(String a) {

        out.println(a);

    }



    static void print(String a) {

        out.print(a);

    }



    static void print(int[] a) {

        for (int i = 0; i < a.length - 1; i++) {

            out.print(a[i] + " ");

        }

        if (a.length > 0) {

            out.println(a[a.length - 1]);

        }

    }



    static void print(List<?> l) {

        for (int i = 0; i < l.size() - 1; i++) {

            out.print(l.get(i) + " ");

        }

        if (!l.isEmpty()) {

            out.println(l.get(l.size() - 1));

        }

    }





    public static class D {

        private final int[] dArray; // 离散化后的数组



        public int index;



        // 初始化方法

        public D(int[] oArray,int n) {

            // 1. 去重

            Set<Integer> set = new HashSet<>();

            for(int i=1;i<=n;i++){

                set.add(oArray[i]);

            }



            // 2. 转换为数组并排序

            dArray = new int[set.size()+1];

            index = 0;

            for (int num : set) {

                dArray[++index] = num;

            }

            Arrays.sort(dArray,1,index+1);

        }



        public int getOld(int x){

            return dArray[x];

        }



        // 获取离散化后的值（二分查找实现）

        public int get(int target) {

            int left = 1;

            int right = index;



            while (left <= right) {

                int mid = left + (right - left) / 2;

                if (dArray[mid] == target) {

                    return mid; // 返回下标 + 1（假设下标从 1 开始）

                } else if (dArray[mid] < target) {

                    left = mid + 1;

                } else {

                    right = mid - 1;

                }

            }



            return -1; // 如果未找到，返回 -1

        }



    }



}