算法学习——数据结构

字典树

把模板背熟

#include <iostream>

using namespace std;

const int N = 100010;

int son[N][26], cnt[N], idx;
char str[N];

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

int query(char *str)
{
    int p = 0;
    for (int i = 0; str[i]; i ++ )
    {
        int u = str[i] - 'a';
        if (!son[p][u]) return 0;
        p = son[p][u];
    }
    return cnt[p];
}

int main()
{
    int n;
    scanf("%d", &n);
    while (n -- )
    {
        char op[2];
        scanf("%s%s", op, str);
        if (*op == 'I') insert(str);
        else printf("%d\n", query(str));
    }

    return 0;
}

如果涉及到多组数据(多棵树的建立),在每次建立的时候都要记得置零

涉及到不同种类的字符串,要写一个getnum函数

字典树的综合模板

【模板】字典树 - 洛谷

#include <iostream>

using namespace std;

const int N =3e6+10;

int son[3000005][65], cnt[3000005], idx;
char str[3000005];

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

void insert(char str[])
{
    int p=0;
    for(int i=0;str[i];i++)
    {
        int j=getnum(str[i]);
        if(!son[p][j])son[p][j]=++idx;
        p=son[p][j];
        cnt[p]++;//由于是累计的一个值,所以标记是每次循环都要更新 
    }
}

int query(char str[])
{
    int p=0;
    for(int i=0;str[i];i++)
    {
        int j=getnum(str[i]);
        if(!son[p][j])return 0;
        p=son[p][j];
    }
    return cnt[p];
}


int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
    	//要置零 
    	for(int i=0;i<=idx;i++)
            for(int j=0;j<=122;j++)
                son[i][j]=0;
        for(int i=0;i<=idx;i++)
            cnt[i]=0;
            idx=0; 
            
    	int a,b;cin>>a>>b;
    	while(a--)
    	{
        scanf("%s",str);
        insert(str);	
		}
		while(b--)
		{
        scanf("%s",str);
        cout<<query(str)<<endl;
		}
        
    }

    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值