字典树模板题

字典树模板:

#include
#include
#include
#include
using namespace std;

const int MAX_S=400005;	//字符串的字符总长度 
int Trie[MAX_S][26],sum[MAX_S],num;
int n,m;
char s[35];

void insert(char s[]);
bool find(char s[],int rt);
int search(char s[]);
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
    {
    	scanf("%s",s);
        insert(s);
    }
    scanf("%d",&m);
    for(int i=1;i<=m;++i)
    {
        scanf("%s",s);
        printf("%d\n",search(s));
    }
}

void insert(char s[])
{
    int u=0,len=strlen(s);
    for(int i=0;i

 

一,HDU-1251-统计难题  :统计前缀字符串个数

Code :

#include
#include
#include
using namespace std;

const int MAX_N=400005;
int num;
char ch[15];
int Trie[MAX_N][30],Sum[MAX_N];

void Insert(char ch[]);
int Search(char ch[]);
int main()
{
	while(gets(ch)&&ch[0]!='\0'){
		Insert(ch);
	}
	while(gets(ch)){
		printf("%d\n",Search(ch));
	}
	
	return 0;
}

void Insert(char ch[])
{
	int u=0,len=strlen(ch);
	for(int i=0;i

二,HDU-2072-单词数 :统计不同单词个数

Code :

#include
#include
#include
using namespace std;

const int MAX_N=50005;
int Trie[MAX_N][30],Sum[MAX_N],num;
string str;

void Insert(string s);
int Find();
int main()
{
	ios::sync_with_stdio(false);
	while(getline(cin,str)){
		if(str=="#")	break;
		memset(Trie,0,sizeof(Trie));
		memset(Sum,0,sizeof(Sum));
		num=0;
		stringstream sin(str);
		while(sin>>str){
			Insert(str);
		}
		cout<

三,POJ-2001-Shortest Prefixes :求唯一标记前缀字符串,只要找到前缀字符串的个数为1即可

Code:

#include
using namespace std;

const int MAX_N=1005;
const int MAX_S=20005;
int Trie[MAX_S][30],Sum[MAX_S],num;
string str[MAX_N];

void Insert(string s);
string Search(string s);
int main()
{
	ios::sync_with_stdio(false);
	int n=0;
	while(cin>>str[n]){
		Insert(str[n++]);
	}
	for(int i=0;i

四,POJ-3630-Phone List : 判断是否有字符串是另一字符串的前缀,在构造时对字符串的元素做标记,以及对最后一个字符做特殊标记,在判断即可

Code :

#include
#include
using namespace std;

const int MAX_S=100005;
int n,num,T;
int Trie[MAX_S][15],Sum[MAX_S];
string str;
bool boo;

bool Insert(string s);
int main()
{
	ios::sync_with_stdio(false);
	cin>>T;
	while(T--){
		memset(Trie,0,sizeof(Trie));
		memset(Sum,0,sizeof(Sum));
		boo=true;	num=0;
		cin>>n;
		for(int i=0;i>str;
			if(boo&&!Insert(str))	boo=false;
		}
		if(boo==true)	cout<<"YES"<

 

你可能感兴趣的:(HDU,POJ,字典树)