【字典树】zoj2876 Phone list

在poj上有同样一道题目,不过很诡异的是,poj上超时了。。。。


//更快的方法应该是建立静态树或者直接进行排序模拟 
#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;

//节点定义 
struct Node{
	Node* ptr[10];
	bool complete[10];
};

void insert(Node* root,char phone_num[15]);
void delete_tree(Node* root); 
void initial(Node* pt);
bool Unique=true;
int main(){
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	Node* root=NULL;
	int t,n;
	char phone_num[15];
	scanf("%d",&t);
	//cin>>t;
	while(t--){
		scanf("%d",&n);
		//cin>>n;
		Unique=true;
		root=new Node;
		initial(root);
		for(int i=0;i<n;i++){
			scanf("%s",phone_num);
			//cin>>phone_num;
			if(Unique==true)
				insert(root,phone_num);			
		}
		if(Unique==true)
			cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
		delete_tree(root);
	}
	//system("pause");
	return 0;
}

//进行节点的插入操作 
void insert(Node* root,char phone_num[15]){
	int len=strlen(phone_num),cur=0;
	Node* tmp=root;	
	while(len--){
		int pos=phone_num[cur++]-'0';
		if(tmp->complete[pos]==true){
			Unique=false;
			return;
		}
		if(tmp->ptr[pos]==NULL){
			tmp->ptr[pos]=new Node;
			initial(tmp->ptr[pos]);
		}
		if(len==0)
			tmp->complete[pos]=true;
		tmp=tmp->ptr[pos];
	}
	for(int i=0;i<10;i++)
		if(tmp->ptr[i]!=NULL)
			Unique=false;			
}

//删除原有的字典树 
void delete_tree(Node* root){
	for(int i=0;i<10;i++){
		if(root->ptr[i]!=NULL)
			delete_tree(root->ptr[i]);
	}
	delete root;	
} 

//初始化一个新生成的节点 
void initial(Node* pt){
	for(int i=0;i<10;i++){
		pt->ptr[i]=NULL;
		pt->complete[i]=false;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值