字典树板子求条谢谢啦

P8306 【模板】字典树

I_Love_DS @ 2024-11-29 22:07:41

#include <bits/stdc++.h>

using namespace std;

const int N = 3000001, S = 65;

int n, q;

int nxt[N][S], cnt;
int is[N];
char a[N];

int check(char x) {
    if (isupper(x)) return x - 'A';
    if (islower(x)) return 26 + x - 'a';
    return 52 + x - '0';
}

void insert(char s[], int len) {
    int now = 0;
    for (int i = 1; i <= len; i++) {
        int x = check(s[i]);
        if (!nxt[now][x]) nxt[now][x] = ++cnt;
        now = nxt[now][x];
        ++is[now];
    }
}

int search(char s[], int len) {
    int now = 0;
    for (int i = 1; i <= len; i++) {
        int x = check(s[i]);
        if (!nxt[now][x]) return 0;
        now = nxt[now][x];
    }
    return is[now];
}

void solve() {
    for (int i = 1; i <= cnt; i++) 
        for (int j = 1; j <= 64; j++) 
            nxt[i][j] = 0;
    for (int i = 1; i <= cnt; i++) is[i] = 0;
    cnt = 0;
    scanf("%d%d", &n, &q);
    for (int i = 1; i <= n; i++) {
        scanf("%s", a + 1);
        int m = strlen(a + 1);
        insert(a, m);
    }
    for (int i = 1; i <= q; i++) {
        scanf("%s", a + 1);
        int m = strlen(a + 1);
        printf("%d\n", search(a, m));
    }
}

int main() {
    int t;
    scanf("%d", &t);
    while (t--) solve();
    return 0;
}

by lowbit @ 2024-11-29 22:24:15

你调用函数那里也要写 a+1 啊@I_Love_DS


by I_Love_DS @ 2024-11-29 22:51:28

@lowbit

好像不对。

具体化的?

提前祝您 NOIP RP++!


by I_Love_DS @ 2024-11-29 22:58:12

@lowbit

原来清空时下标应该从 0 起始的。

谢谢!虽然你没有给我根本地解决问题,但你的态度很好,希望给我指正错误!谢谢!祝您 NOIP RP++!!


|