hdu(2846)Repository

本文介绍了一种使用字典树实现商品名称搜索模拟的方法。针对大量商品名存储于数据库中,用户通过输入部分字符串来查询匹配的商品数量。利用字典树高效地存储所有可能的子串,并统计每个子串出现的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Problem Description
When you go shopping, you can search in repository for avalible merchandises by the computers and internet. First you give the search system a name about something, then the system responds with the results. Now you are given a lot merchandise names in repository and some queries, and required to simulate the process.
 

Input
There is only one case. First there is an integer P (1<=P<=10000)representing the number of the merchanidse names in the repository. The next P lines each contain a string (it's length isn't beyond 20,and all the letters are lowercase).Then there is an integer Q(1<=Q<=100000) representing the number of the queries. The next Q lines each contains a string(the same limitation as foregoing descriptions) as the searching condition.
 

Output
For each query, you just output the number of the merchandises, whose names contain the search string as their substrings.
 

Sample Input
20 ad ae af ag ah ai aj ak al ads add ade adf adg adh adi adj adk adl aes 5 b a d ad s
 

Sample Output
0 20 11 11 2


题解:字典树,把每一个字符串的字串都用字典树保存下来,并且记录下每一个子串的个数,但是要注意每个字符串可能有相同的字串,此时只加一次。例如ababc,ab只加一次

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

struct Node
{
	int id;
	int num;
	Node* next[26];
	Node()
	{
		id = -1;
		num = 0;
		for(int i = 0;i < 26;i++)
		{
			next[i] = NULL;
		}
	}
};

Node* root;

void insert(char* s,int k)
{
	int len = strlen(s);
	Node* p = root;
	for(int i = 0;i < len;i++)
	{
		if(p->next[s[i] - 'a'] == NULL)
		{
			Node* q = new Node();
			q->id = k;
			q->num = 1;
			p->next[s[i] - 'a'] = q;
		}
		p = p->next[s[i] - 'a'];  
		if(p->id != k)     
		{
			p->id = k; //该字符串中该子字符已经出现了 
		    p->num++;  //该字串个数加一 
		}
	}
}

int find(char* s)
{
	int len = strlen(s);
	Node* p = root;
	for(int i = 0;i < len;i++)
	{
		if(p->next[s[i] - 'a'] == NULL)
		{
			return 0;
		}
		p = p->next[s[i] - 'a'];
	}
	return p->num;
}

void del(Node*& p)
{
	for(int i = 0;i < 26;i++)
	{
		if(p->next[i] != NULL)
		{
			del(p->next[i]);
		}
	}
	delete p;
}

int main()
{
	int n;
	while(scanf("%d",&n) != EOF)
	{
		root = new Node();
		char s[100];
		for(int i = 0;i < n;i++)
		{
			scanf("%s",s);
			for(int j = 0;s[j] != '\0';j++)
			{
				insert(s + j,i);
			}
		}
		int q;
		scanf("%d",&q);
		for(int i = 0;i < q;i++)
		{
			scanf("%s",s);
			printf("%d\n",find(s));
		}
		del(root);
	}
	
	
	return 0;
 } 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值