HDU 1671 Phone List(指针字典树或数组字典树实现)

Phone List

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23480    Accepted Submission(s): 7893


Problem Description
Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.
 

Input
The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.
 

Output
For each test case, output “YES” if the list is consistent, or “NO” otherwise.
 

Sample Input
 
   
 
   
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output
 
   
NO
YES
题意:所给电话表中,如果有一个字符串是另一个字符串的前缀,输出NO,否则YES
#include
#include 
#include
using namespace std;
#define MAX 10
struct Tree{
	Tree *next[MAX];
	int v;
};
Tree *root;
void careTree(char *str)
{//构建 
	int len=strlen(str);
	Tree *p=root,*q;
	for(int i=0;inext[id]==NULL)
		{
			q=(Tree*)malloc(sizeof(Tree));
			q->v=1;//初始为1 
			for(int j=0;jnext[j]=NULL;
			}
			p->next[id]=q;
			p=p->next[id];
		}
		else
		{
			p->next[id]->v++;
			p=p->next[id];
		}
	}
	p->v=-1;//若是结尾,将v改为-1表示 
}
int findTree(char *str)
{//查找 
	int len=strlen(str);
	Tree *p=root;
	for(int i=0;inext[id];
		if(p==NULL)//若是空树返回0 
			return 0;
		if(p->v==-1)//树中的某个字符串是此串的前缀 
			return -1;
	}
	return -1;//此串是树中某个串的前缀 
}
int dealTree(Tree *T)
{//释放空间 
	if(T==NULL)
		return 0;
	for(int i=0;inext[i]!=NULL)
			dealTree(T->next[i]);
	}
	free(T);
	return 0;
}
void init()
{
	root=(Tree *)malloc(sizeof(Tree));
	root->v=1; 
	for(int i=0;inext[i]=NULL;
	return; 
} 
int main()
{
	 int t;
	 scanf("%d",&t);
	 while(t--)
	 {
	 	init();//初始化根节点 
	 	char str[15];
	 	int n;
	 	scanf("%d",&n);
	 	int flag=0;
	 	for(int i=0;i

数组字典树实现(今天终于搞对了!):

#include 
#include 
#include 
using namespace std;
struct node{
    int next[10];
    int end;//是否以此字符结尾 
    int v;//字母出现的次数 
    void init(){//初始化 
        v=0;
        end=0;
        //数组赋值视情况而定,查前缀赋0
		//赋-1出错 
        memset(next,0,sizeof(next));
    }
};
//比要求的多开了10倍,不然时间超限
//不知道为啥 
struct node L[100005];
int tot;//总结点数 
void add(char a[])
{//建树 
    int now=0;
    int len=strlen(a);
    for(int i=0;i


你可能感兴趣的:(字符串处理)