hdu1305之字典树

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
using namespace std;

const int MAX=2;
bool flag;

struct TrieNode{
	bool mark;//标记一个单词 
	TrieNode *next[MAX];
	TrieNode(){
		mark=false;
		memset(next,0,sizeof next);
	}
}root;

void InsertNode(char *a){
	int k=0;
	TrieNode *p=&root;
	while(a[k]){
		if(!p->next[a[k]-'0'])p->next[a[k]-'0']=new TrieNode;
		else if(!a[k+1])flag=false;//a是其他字符串的字串 
		p=p->next[a[k++]-'0'];
		if(p->mark)flag=false;//其他字符串是a的字串 
	} 
	p->mark=true;
}

void Free(TrieNode *p){
	for(int i=0;i<2;++i){
		if(p->next[i])Free(p->next[i]); 
	}
	delete p;
} 

int main(){
	char s[10];
	int num=0;
	while(cin>>s){
		flag=true;
		while(s[0] != '9'){
			if(flag)InsertNode(s);
			cin>>s;
		}
		if(flag)cout<<"Set "<<++num<<" is immediately decodable"<<endl;
		else cout<<"Set "<<++num<<" is not immediately decodable"<<endl;
		for(int i=0;i<2;++i)if(root.next[i])Free(root.next[i]); 
		//Free(&root);//清空本次的字符串(节点)
		root.next[0]=root.next[1]=NULL;
	}
	return 0;
}

你可能感兴趣的:(hdu1305之字典树)