《算法竞赛-训练指南》-第三章-Trie

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

const int MAXNODE = 1000000 + 11;

const int SEGMA_SIZE = 26;

struct Trie
{
	int ch[MAXNODE][SEGMA_SIZE];
	int val[MAXNODE];
	int size;
	Trie()
	{
		size = 1;
		memset(ch[0], 0, sizeof(ch[0]));
	}
	void clear()
	{
		size = 1;
		memset(ch[0], 0, sizeof(ch[0]));
	}
	int idx(char c) // 求出字符所对应的id 
	{
		return c - 'a';
	}
	void insert(char *s, int v)
	{
		int n = strlen(s);
		int u = 0;
		for (int i = 0; i < n; i++)
		{
			int id = idx(s[i]);
			if (!ch[u][id])
			{
				memset(ch[size], 0, sizeof(ch[size]));
				val[size] = 0;
				ch[u][id] = size++;
			}
			u = ch[u][id];
		}
		val[u] = v;
	}
	int search(char *s)
	{
		int n = strlen(s);
		int u = 0;
		for (int i = 0; i < n; i++)
		{
			int id = idx(s[i]);
			if (!ch[u][id])
			{
				return 0;
			}
			u = ch[u][id];
		}
		if (val[u] == 1)
		{
			return 1;
		}
	}
		
}trie;

int main()
{
	char str[111];
	int N, M;
	while (scanf("%d%d", &N, &M) != EOF)
	{
		trie.clear();
		for (int i = 0; i < N; i++)
		{
			scanf("%s", str);
			trie.insert(str, 1);
		}
		for (int i = 0; i < M ; i++)
		{
			scanf("%s", str);
			int ans = trie.search(str);
			if (ans == 1)
			{
				printf("The string exists\n");
			}
			else
			{
				printf("The string doesn`t exist\n");
			}
		}
	}
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值