字典树模版求调
查看原帖
字典树模版求调
270854
二叉苹果树楼主2022/11/23 01:40

思路和第一篇题解相同,但是5WA + 1TLE求助

#include<bits/stdc++.h>
#define MAXN 3000005
int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while(!isdigit(ch))
    {
        if(ch == '-')
            f = -1;
        ch = getchar();
    }
    while(isdigit(ch))
    {
        x = (x << 1) + (x << 3) + ch - '0';
        ch = getchar();
    }
    return x * f;
}

char s[MAXN];
int trie[MAXN][65], sum[MAXN], tot;

int change(char c)
{
    if(c >= 'A' && c <= 'Z')
        return c - 'A';
    else if(c >= 'a' && c <= 'z')
        return c - 'a' + 26;
    else
        return c - '0' + 52;
}

void insert(char *str)
{
    int u = 0;
    int len = strlen(str);
    for(int i = 0; i < len; i++)
    {
        int a = change(str[i]);
        if(trie[u][a] == 0)
            trie[u][a] = ++tot;
        u = trie[u][a];
        sum[u]++;
    }
}

int find(char *str)
{
    int u = 0;
    int len = strlen(str);
    for(int i = 0; i < len; i++)
    {
        int a = change(str[i]);
        if(trie[u][a] == 0)
            return 0;
        u = trie[u][a];
    }
    return sum[u];
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0), std::cout.tie(0);
    int t = read();
    while(t--)
    {
        int n = read(), q = read();
        for(int i = 0; i <= tot; i++)
        {
            for(int j = 0; j <= 65; j++)
                trie[i][j] = 0;
            sum[i] = 0;
        }
        tot = 0;
        for(int i = 1; i <= n; i++)
        {
            scanf("%s", s);
            insert(s);
        }
        for(int i = 1; i <= q; i++)
        {
            scanf("%s", s);
            std::cout << find(s) << std::endl;
        }
    }
    return 0;
}
2022/11/23 01:40
加载中...