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;
}


posted on 2012-07-16 22:09  java课程设计例子  阅读(237)  评论(0编辑  收藏  举报