84分倒数第二个测试点超时,求助

P8306 【模板】字典树

Mark_666 @ 2024-07-02 15:44:17

#include <iostream>
#include <string.h>
using namespace std;
const int N = 3000005;
int n,m;
int trie[N][65], cnt[N], id;
string temp;
int ans;
int T;
char pd(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;
}
void insert(string s)
{
    int p = 0;
    for (int i = 0; i < s.size(); i++)
    {
        int x = pd(s[i]);
        if (trie[p][x] == 0) trie[p][x] = ++id;
        p = trie[p][x];
        cnt[p]++;
    }

}
int find(string s)
{
    int p = 0;
    for (int i = 0; i < s.size(); i++)
    {
        int x = pd(s[i]);
        if (trie[p][x] == 0) return 0;
        p = trie[p][x];
    }
    if (cnt[p]) return cnt[p];
    else return 0;
}
void init()
{
    for(int i=0;i<=id;i++)
        for(int j=0;j<65;j++)
            trie[i][j]=0;       
    memset(cnt,0,sizeof(cnt));
    id=0;
    ans=0;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>T;
    while(T--)
    {
        init();
        cin>>n>>m;
        for(int i=1;i<=n;i++)
        {
            cin>>temp;
            insert(temp);
        }
        for(int i=1;i<=m;i++)
        {
            cin>>temp;
            cout<<find(temp)<<'\n';
        }
    }

    return 0;
}

by Miss_SGT @ 2024-07-02 15:51:49

init()里面有个memset,改成循环就行了


by Mark_666 @ 2024-07-23 10:09:23

@Miss_SGT 谢谢,之前一直忘记回复你了,抱歉


by Miss_SGT @ 2024-07-23 10:54:05

@Mark_666 抽象,你家网有点慢啊qwq


by Mark_666 @ 2024-07-23 14:58:42

@Miss_SGT 不是。。。是看到之后就直接去更改了,之后就忘记回复你了


|