NYOJ 163 || HDU 1671 || HDU 1305

题目链接:CLICK HERE

题目链接:CLICK HERE

最先用到的思路是先用一个数组str1[]把第一个号码存起来,然后把剩余n-1个号码存进树里,再find(str1)。虽然能过样例,但是提交就RuntimeError。因为这样做只能判断str1是不是其他号码的前缀,如果有比str1短的号码做为str1的前缀,就会RuntimeError。不但要判断str1是不是其他号码的前缀,还要判断其他的号码是不是str1的前缀。

所以,把每个号码的每位数字出现的次数记录下来,再查找每个号码出现的次数。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
	int count;
	node *next[11];
};
node *root;
char str1[100009][15];
node *build()
{
	node *current=new node;
	for (int i=0;i<11;i++)
		current->next[i]=NULL;
	current->count=0;
	return current;
}
void insert(char *s)
{
	node *current=root;
	int len=strlen(s);
	for (int i = 0; i < len; i++)
	{
		if (current->next[s[i]-'0']==NULL)
		{
			current->next[s[i]-'0']=build();
			current=current->next[s[i]-'0'];
		}
		else
		{
			current=current->next[s[i]-'0'];
		}
		current->count++;
	}
}
int find(char *s)
{
	node *current=root;
	int len=strlen(s);
	for (int i=0;i<len;i++)
	{
		current=current->next[s[i]-'0'];
	}
	return current->count;
}
void deel(node *p)
{
	for (int i=0;i<11;i++)
	{
		if (p->next[i]!=NULL)
			deel(p->next[i]);
	}
	free(p);
}
int main()
{
	int t;
	scanf("%d",&t);
	while (t--)
	{
		int n,flag=0;
		root=build();
		scanf("%d",&n);
		for (int i=0;i<n;i++)
		{
			scanf("%s",str1[i]);
			insert(str1[i]);
		}
		for (int i=0;i<n;i++)
		{
			int x=find(str1[i]);
			if (x!=1)
			{
				flag=0;
				break;
			}
			flag=1;
		}
		if (flag==0)
			printf("NO\n");
		else
			printf("YES\n");
		deel(root);
	}
	return 0;
}

HDU   1305

和上两题一样,只需修改代码。但刚开始的时候把输入弄错了,造成了死循环。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
	int count;
	node *next[11];
};
node *root;

node *build()
{
	node *current=new node;
	for (int i=0;i<11;i++)
		current->next[i]=NULL;
	current->count=0;
	return current;
}
void insert(char *s)
{
	node *current=root;
	int len=strlen(s);
	for (int i = 0; i < len; i++)
	{
		if (current->next[s[i]-'0']==NULL)
		{
			current->next[s[i]-'0']=build();
			current=current->next[s[i]-'0'];
		}
		else
		{
			current=current->next[s[i]-'0'];
		}
		current->count++;
	}
}
int find(char *s)
{
	node *current=root;
	int len=strlen(s);
	for (int i=0;i<len;i++)
	{
		current=current->next[s[i]-'0'];
	}
	return current->count;
}
void deel(node *p)
{
	for (int i=0;i<11;i++)
	{
		if (p->next[i]!=NULL)
			deel(p->next[i]);
	}
	free(p);
}
int main()
{
	char str[100009][15];
	int F=1;
	while (~scanf("%s",str[0]))
	{
		int k=1,flag=0;
		root=build();
		insert(str[0]);
	    while (1)
		{
	     	scanf("%s",str[k]);
		    if (str[k][0]=='9')
			   break;
			else
			{
				insert(str[k]);
		        k++;
			}
		}
		for (int i=0;i<k;i++)
		{
			if (find(str[i])!=1)
			{
				flag=0;
				break;
			}
			flag=1;
		}
		if (flag==0)
			printf("Set %d is not immediately decodable\n",F++);
		else
			printf("Set %d is immediately decodable\n",F++);
		deel(root);
	}
	return 0;
}


 


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