蒟蒻求助 MLE

P8306 【模板】字典树

hbusdy @ 2022-05-11 10:47:47

求助

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static int N = 3000010, idx;
    static int[][] son = new int[N][130];
    static int[] pre = new int[N];

    static void insert(String str) {
        int p = 0;
        for (int i = 0; i < str.length(); i++) {
            int u = str.charAt(i);
            if (son[p][u] == 0) {
                son[p][u] = ++idx;
            }
            p = son[p][u];
            pre[p]++;
        }
    }

    static int query(String str) {
        int p = 0;
        int sum = 0;
        for (int i = 0; i < str.length(); i++) {
            int u = str.charAt(i);
            if (son[p][u] == 0) return 0;
            p = son[p][u];
        }
        return pre[p];
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for (int i = 0; i < n; i++) {
            int a, b;
            a = s.nextInt();
            b = s.nextInt();
            for (int j = 0; j < a; j++) {
                String str = s.next();
                insert(str);
            }
            for (int j = 0; j < b; j++) {
                String str = s.next();
                System.out.println(query(str));
            }
            for (int[] x : son) {
                Arrays.fill(x, 0);
            }
            Arrays.fill(pre, 0);

        }
    }
}

|