HDU 1305 字典树


题意:给出二进制字符串,问是否有相同的前缀。。。。

#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<map>
#include<cmath>
#include<iostream>
#include <queue>
#include <stack>
#include<algorithm>
#include<set>
using namespace std;
#define INF 1e8
#define eps 1e-8
#define LL long long
#define maxn 2
#define mol 1000000007
char s[110][11];

struct Trie
{
   Trie *next[maxn];
   int v;
}root;
void creatTrie(char *str)
{
   int len = strlen(str);
   Trie *p = &root,*q;
   for(int i=0;i<len ;i++)
   {
      int id =str[i]-'0';
	  if (p->next[id]==NULL)
	  {
	    q=(Trie *)malloc(sizeof(Trie));
		q->v=1;
		for(int j=0;j<maxn;j++)
		    q->next [j]=NULL;
		p->next [id]=q;
		p=q;
	  }
	  else
	  {
		 p=p->next[id];
		 p->v++;
	  }
   }
}
int find (char *str)
{
    int len = strlen(str);
	Trie *p=&root;
	for(int i=0;i<len;i++)
	{
	    int id = str[i]-'0';
		if(p->next[id])
		p = p->next[id];
		else return 0;
	}
	return p->v ;

}
int main()
{
	int i,j,n=0;
	char ch[20];
	while(gets(s[0])&&s[0][0]!='\0')
	{
		for(i=0;i<maxn;i++)
			root.next [i]=NULL;
		creatTrie(s[0]);
		i=1;n++;
		while(gets(s[i])&&s[i][0]!='9')
		{
			creatTrie(s[i]);
			i++;
		}
		int flag=0;
		for(j=0;j<i;j++)
		{
			if(find(s[j])>1)
			{
				flag=1;
				printf("Set %d is not immediately decodable\n",n);
				break;
			}
		}
		if(!flag)
			printf("Set %d is immediately decodable\n",n);
	}
return 0;
}
/*
01
10
0010
0000
9
01
10
010
0000
9
01
10
9
10
10
100
9



Set 1 is immediately decodable
Set 2 is not immediately decodable
*/



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