RE求调整

P8306 【模板】字典树

FASTergood @ 2024-06-06 21:35:34

RE求调整

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 3000005;
int son[N][65], cnt[N], idx;
char str[N];
void insert(char* str)
{

    int p = 0;
    for (int i = 0;str[i];i++)
    {
        int u = str[i] - '0';
        if (!son[p][u])son[p][u] = ++idx;
        p = son[p][u];
        cnt[p]++;
    }

}
int que(char* str)
{
    int p = 0;
    for (int i = 0;str[i];i++)
    {
        int u = str[i] - '0';
        if (!son[p][u])return 0;
        p = son[p][u];
    }
    return cnt[p];
}
int main()
{
    cin.tie(0);cout.tie(0);
    ios_base::sync_with_stdio;
    int m;
    cin >> m;
    while (m--)
    {
        int t, e;
        cin >> t >> e;
     for(int i=0;i<=idx;i++)
            cnt[i]=0;
        while (t--)
        {
            cin >> str;
            insert(str);
        }
        while (e--)
        {
            cin >> str;
            cout << que(str) << endl;
        }

    }
    return 0;
}

by cosf @ 2024-06-06 21:46:12

你多测 idx 和 son 没清空。

还有 ios::sync_with_stdio 是个函数,不调用是什么情况。


by FASTergood @ 2024-06-10 20:13:53

@cosf 谢谢大佬,完美通过

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 3000005;
int son[N][122], cnt[N], idx;
char str[N];
void insert(char* str)
{

    int p = 0;
    for (int i = 0;str[i];i++)
    {
        int u = str[i] - '0';
        if (!son[p][u])son[p][u] = ++idx;
        p = son[p][u];
        cnt[p]++;
    }

}
int que(char* str)
{
    int p = 0;
    for (int i = 0;str[i];i++)
    {
        int u = str[i] - '0';
        if (!son[p][u])return 0;
        p = son[p][u];
    }
    return cnt[p];
}
int main()
{
    cin.tie(0);cout.tie(0);
    ios_base::sync_with_stdio(false);
    int m;
    cin >> m;
    while (m--)
    {
        int t, e;
        cin >> t >> e;

        while (t--)
        {
            cin >> str;
            insert(str);
        }
        while (e--)
        {
            cin >> str;
            cout << que(str) << endl;
        }
        for (int i = 0;i <= idx;i++)
        {
            cnt[i] = 0;
        }

        for (int i = 0;i <= idx;i++)
            for (int j = 0;j <= 122;j++)
                son[i][j] = 0;
        idx = 0;
    }
    return 0;
}

|