zoj 1808 Immediate Decodability

字典树实现
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
#define ls rt<<1
#define rs ls1
#define lson l,mid,ls
#define rson mid+1,r,rs
#define middle (l+r)>>1
#define eps (1e-9)
#define clr_all(x,c) memset(x,c,sizeof(x))
#define clr(x,c,n) memset(x,c,sizeof(x[0])*(n+1))
#define MOD 1000000007
#define inf 100000007
#define pi acos(-1.0)
#define M 200000+5
typedef struct Trie{
	Trie *next[2];
	int v;
} ;
Trie *root;
int f;
char w[M][12];
Trie *createNode(){
	Trie *p;
	p=(Trie *)malloc(sizeof(Trie));
	p->v=0;
	p->next[0]=NULL;p->next[1]=NULL;
	return p;
}
void release(Trie *p){
	int i;
	if(p->next[0]!=NULL)
		release(p->next[0]);
	if(p->next[1]!=NULL)
		release(p->next[1]);
	free(p);
}
int insert(char *st){
	int i,len=strlen(st);
	Trie *p=root;
	for(i=0;i<len;i++){
		int id=st[i]-'0';
		if(p->next[id]==NULL)
			p->next[id]=createNode();
		p=p->next[id];
	}
	p->v=1;
}
void search(char *st){
	int i,len=strlen(st);
	Trie *p=root;
	for(i=0;i<len;i++){
		int id=st[i]-'0';
		p=p->next[id];
	}
	if(p->next[0]!=NULL||p->next[1]!=NULL)	f=1;
}
int main(){
    int i,j,cnt=1;char st[12];
    root=createNode();
    i=0;f=0;
    while(scanf("%s",st)!=EOF){
		if(strcmp(st,"9")==0){
			for(j=0;j<i;j++)search(w[j]);
			if(f==0)
				printf("Set %d is immediately decodable\n",cnt++);
			else 
				printf("Set %d is not immediately decodable\n",cnt++);
			release(root);
			root=createNode();
			f=0;i=0;
		}else{
			strcpy(w[i++],st);
			insert(st);
		}
	}
    return 0;
}

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