POJ2001Trie树的运用

61 篇文章 0 订阅
//字符串的前缀处理问题:Trie树的运用
//同时前缀标出让其没有歧义:思路就是从子串中在Trie树中找到能够唯一标示的第一个字符为止
//Accepted	276K	16MS
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

typedef struct node{  
	int L;//以当前开头的词的数目
	char value;
	node*child;
	node* next;
}*Node;


Node GTireTree;//地图存储

static int n;
static char str[1002][22];
static void initTree()
{
	GTireTree = (Node)malloc(sizeof(node));
	GTireTree->child = NULL;
	GTireTree->next = NULL;
	GTireTree->value = '0';
	GTireTree->L = 0;
}

static void addWord(char*str)
{
	int len = strlen(str);
	Node p = GTireTree;
	p->L++;
	for (int i=0;i<len;++i)
	{
		char ch = str[i];
		Node d = p->child;
		if (d==NULL)
		{
			Node tnode = (Node)malloc(sizeof(node));
			tnode->child = NULL;
			tnode->next = NULL;
			tnode->value = ch;
			p->child = tnode;
			tnode->L = 1;
			d = tnode;
			//printf("生成结点%c ",ch);
		}
		else{
			Node last;
			while(d!=NULL&&d->value!=ch)
			{
				last = d;
				d = d->next;
			}
			if (d==NULL)
			{
				d = (Node)malloc(sizeof(node));
				d->child = NULL;
				d->next = NULL;
				d->value = ch;
				d->L = 1;
				last->next = d;
				//printf("生成结点%c ",ch);
			}
			else
			{
				d->L++;
				//printf("已经存在结点%c ",ch);
			}
		}

		p = d;

	}
	//printf("\n");
}



static int search(char*str)
{
	int len = strlen(str);
	Node p = GTireTree;
	int time = 0;
	for (int i=0;i<len;++i)
	{
		char ch = str[i];
		Node d = p->child;

		while(d!=NULL&&d->value!=ch)
			d = d->next;
		if (d==NULL)
			break;
		if (i==len-1)
			time = d->L;
		p = d;
	}

	return time;

}

static void solve()
{
	int i,j;
	for (i=0;i<n;++i)
	{
		int len = strlen(str[i]);
		char strdest[22];
		int times = 0;
		for (j=1;j<=len;++j)
		{
			strncpy(strdest,str[i],j);
			strdest[j] = '\0';
			times = search(strdest);
			if (times==1)
			 break;
		}
		printf("%s",str[i]);
		if (j>=len)
		{
			printf(" %s\n",str[i]);
		}
		else if (times==1)
		{
			printf(" %s\n",strdest);
		}
	}
}


int main()
{
	
	initTree();
	n = 0;
	while(scanf("%s",str[n])!=EOF)
	{
		addWord(str[n]);
		n++;
	}
	solve();

	return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值