HDU1251(Trie树入门)

注意new的时候要初始化。


动态new申请:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

struct node
{
    int total;
    struct node *next[26];
    node()
    {
        total=0;
        memset(next,0,sizeof(next));
    }
}*R;

int length;
char str[15];
void insert(struct node *root,int pos)
{
    int i;
    if (pos==length)
        return;
    if (root->next[str[pos]-'a']==NULL)
    {
        for (i=pos;i<length;i++)
        {
            root->next[str[i]-'a']=new struct node;
            root->next[str[i]-'a']->total++;
            root=root->next[str[i]-'a'];
        }
    }
    else
    {
        root->next[str[pos]-'a']->total++;
        insert(root->next[str[pos]-'a'],pos+1);
    }
}

int finds(struct node *root,int pos)
{
    if (pos==length)
        return root->total;
    else if (root->next[str[pos]-'a']==NULL)
        return 0;
    return finds(root->next[str[pos]-'a'],pos+1);
}

int main()
{
    R=new struct node;
    while (1)
    {
        scanf("%s",str);
        getchar();
        length=(int)strlen(str);
        insert(R,0);
        if (cin.peek()=='\n')
            break;
    }
    while (scanf("%s",str)!=EOF)
    {
        length=(int)strlen(str);
        printf("%d\n",finds(R,0));
    }
}


预创建数组:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

struct node
{
	int total;
	int next[26];
}R[500005];

int length;
char str[15];
int counter=1;

void insert()
{
	int index=0;
	int i;
	for (i=0;i<length;i++)
	{
		if (R[index].next[str[i]-'a']==0)
			R[index].next[str[i]-'a']=counter++;
		R[R[index].next[str[i]-'a']].total++;
		index=R[index].next[str[i]-'a'];
	}
}

int find()
{
	int index=0;
	int i;
	for (i=0;i<length;i++)
	{
		if (R[index].next[str[i]-'a']==0)
			return 0;
		index=R[index].next[str[i]-'a'];
	}
	return R[index].total;
}

int main()
{
	while (1)
	{
		scanf("%s",str);
		getchar();
		length=(int)strlen(str);
		insert();
		if (cin.peek()=='\n')
			break;
	}
	while (scanf("%s",str)!=EOF)
	{
		length=(int)strlen(str);
		printf("%d\n",find());
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值