`
java-mans
  • 浏览: 11342998 次
文章分类
社区版块
存档分类
最新评论

HDU-1075-What Are You Talking About

 
阅读更多

HDU-1075-What Are You Talking About

http://acm.hdu.edu.cn/showproblem.php?pid=1075

字典树

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
struct node
{
	int count;
	node *childs[26];
	char tran[15];
	node()
	{
		count=0;
	    for(int i=0;i<26;i++)
		childs[i]=NULL;
		memset(tran,0,sizeof(tran));
	}
};
node *root,*current,*newnode;
void insert(char *str,char *s)
{
	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];
		else
		{
			newnode=new node;
			current->childs[m]=newnode;
			current=newnode;
		}
	}
	current->count=1;
	strcpy(current->tran,s);
}
string search(string str)
{
	int i,m,flag;
	current=root;
	flag=1;
	for(i=0;i<str.length();i++)
	{
		m=str[i]-'a';
		if(current->childs[m]==NULL)
		{
			flag=0;
			break;
		}
        current=current->childs[m];
	}
	if(flag&&i==str.length()&¤t->count==1)
	return current->tran;
	return str;
}
int main()
{
	int i,len;
	char st[15],ed[15];
	char ss[3005];
	string word,ans;
	root=new node;
	scanf("%s",st);
	while(scanf("%s",st),strcmp(st,"END"))
	{
		scanf("%s",ed);
		insert(ed,st);
	}
	scanf("%s",st);
	getchar();
	while(gets(ss),strcmp(ss,"END"))
	{
		len=strlen(ss);
		ans="";
		word="";
		for(i=0;i<len;i++)
		{
			if(ss[i]>='a'&&ss[i]<='z')
			word+=ss[i];
			else
			{
				ans+=search(word);
				word="";
				ans+=ss[i];
			}
		}
		printf("%s\n",ans.c_str());
	}
	return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics