POJ-2001-Shortest Prefixes

POJ-2001-Shortest Prefixes

http://poj.org/problem?id=2001

找出能唯一标示一个字符串的最短前缀,如果找不出,就输出该字符串

用字典树即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
char list[1005][25];
struct node
{
	int count;
	node *childs[26];
	node()
	{
		count=0;
		int i;
		for(i=0;i<26;i++)
		childs[i]=NULL;
	}
};
node *root=new node;
node *current,*newnode;
void insert(char *str)
{
	int i,m;
	current=root;
	for(i=0;i<strlen(str);i++)
	{
		m=str[i]-'a';
		if(current->childs[m]!=NULL)
		{
			current=current->childs[m];
			++(current->count);
		}
		else
		{
			newnode=new node;
			++(newnode->count);
			current->childs[m]=newnode;
			current=newnode;
		}
	}
}
void search(char *str)
{
	int i,m;
	char ans[25];
	current=root;
	for(i=0;i<strlen(str);i++)
	{
		m=str[i]-'a';
        current=current->childs[m];
		ans[i]=str[i];
		ans[i+1]='\0';
		if(current->count==1)    //可以唯一标示该字符串的前缀
		{
			printf("%s %s\n",str,ans);
			return;
		}
	}
	printf("%s %s\n",str,ans);  // 否则输出该字符串
}
int main()
{
	int i,t=0;
	while(scanf("%s",list[t])!=EOF)
	{
		insert(list[t]);
		t++;
	}
	for(i=0;i<t;i++)
	search(list[i]);
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值