hdu 2846Repository

Repository

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3413    Accepted Submission(s): 1283


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
 

Source
 

题目大意及思路:

就是查一个字符串出现的次数,假设有字符串addd,查d出现的次数,d出现次数是1而不是3,也就是说不管母串中出现了几个子串,子串只相当与出现1次;
用字典树做要做一个标记mark;

ac代码:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
struct TrieNode{
	int data;
	int mark;       //做标记 
	TrieNode *next[26];
	TrieNode(){
		data=0;
		mark=-1;
		memset(next,0,sizeof(next));
	}
}; 
TrieNode *root=NULL;
void Build(char *c,int k){
	int i,v,l=strlen(c);
	TrieNode *p=root;
	TrieNode *q=NULL;
	for(i=0;i<l;i++){
		v=c[i]-'a';
		if(p->next[v]==NULL){
			q=new TrieNode;
			q->data=1;
			q->mark=k;
			p->next[v]=q;
		}
		p=p->next[v];
		if(p->mark!=k){
			p->mark=k;
			p->data++;    //如果不是同一个串的话,data自加1,否则不加,避免重复 
		}
	}
} 
int Find(char *c){
	int i,v,l=strlen(c);
	TrieNode *p=root;
	for(i=0;i<l;i++){
		v=c[i]-'a';
		if(p->next[v]==NULL)
		{
			return 0;break;
		}	
		else p=p->next[v];
	}
	return p->data;
}
void Delate(TrieNode *root){
	for(int i=0;i<26;i++)
	if(root->next[i])
	Delate(root->next[i]);
	delete(root);
}
int main()
{
	int Q,P,i,j;
	char c[21];
	root=new TrieNode;
	scanf("%d",&P);
	for(i=0;i<P;i++)
	{
		scanf("%s",c);
		int l=strlen(c);
		for(j=0;j<l;j++)
		Build(c+j,i);      //插入字符串和字符串的序号,作为标记
	}
	scanf("%d",&Q);
	for(i=0;i<Q;i++)
	{
		scanf("%s",c);
		printf("%d\n",Find(c));
	}
	Delate(root);
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值