52pts 求助 TLE on #3,4,5

P8306 【模板】字典树

lihugang @ 2024-10-25 14:00:02

52pts 求助 TLE on #3,4,5

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct  _node
{
    _node * map[63];
    int value = 0;
} node;

inline auto mapping(char x) {
    if (x >= 'A' && x <= 'Z') return x - 'A';
    else if(x >= 'a' && x <= 'z') return x - 'a' + 26;
    else return x - '0' + 52;
}
node nodes[2000008];

char input[3000008];

auto main(void) -> int {
    #ifdef DEBUG
    freopen("8306.in", "r", stdin);
    #endif
    int countOfTestcases;
    int usedNodes = 0;

    scanf("%d", &countOfTestcases);

    node root;

    for (int i = 0; i < 63; i++) root.map[i] = NULL;

    while (countOfTestcases--) {

        int countOfPatterns, countOfQueries;

        scanf("%d %d", &countOfPatterns, &countOfQueries);

        for (int i = 0; i < countOfPatterns; i++) {
            scanf("%s", input);
            auto length = strlen(input);

            node * cur = &root;

            for (int j = 0; j < length; j++) {
                input[j] = mapping(input[j]);
                if (!cur->map[input[j]]) {
                    cur->map[input[j]] = nodes + (usedNodes++);
                    for (int k = 0; k < 63; k++) cur->map[input[j]]->map[k] = NULL;
                    cur->map[input[j]]->value = 0;
                }
                cur = cur->map[input[j]];
                cur->value++;
            }
        }

        for (int i = 0; i < countOfQueries; i++) {
            scanf("%s", input);
            auto length = strlen(input);

            node * cur = &root;

            bool ok = true;

            for (int j = 0; j < length; j++) {
                input[j] = mapping(input[j]);
                if (!cur->map[input[j]]) {
                    printf("0\n");
                    ok = false;
                    break;
                }
                cur = cur->map[input[j]];
            }

            if (ok)
                printf("%d\n", cur->value);
        }

        for (int i = 0; i < usedNodes; i++) nodes[i].value = 0;
    }
    return 0;
}

|