HDOJ Hat’s Words 1247【经典字典树】

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9643    Accepted Submission(s): 3446


Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
 

Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
 

Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
 

Sample Input
   
   
   
   
a ahat hat hatword hziee word
 

Sample Output
   
   
   
   
ahat hatword
 

Author
戴帽子的
 

Recommend
Ignatius.L   |   We have carefully selected several similar problems for you:   1671  1298  2846  1305  2222 

建树。

拆分单词  然后在字典树里查找拆分后的两个单词


#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAX 1000000+1000
using namespace std;
int c[MAX][27];
bool v[MAX];
int tot;
char st[50100][100];
void init()
{
	tot=1;
	memset(c[0],0,sizeof(c[0]));
	memset(v,false,sizeof(v));
}
int insert(char *s)
{
	int l=strlen(s);
	int u=0;
	for(int i=0;i<l;i++)
	{
		int temp=s[i]-'a';
		if(!c[u][temp])
		{
			memset(c[tot],0,sizeof(c[tot]));
			v[tot]=0;
			c[u][temp]=tot++;
		}
		u=c[u][temp];
	}
	v[u]=1;  //记录每个单词最后一个字母。 
}
bool search(char *s)
{
	int l=strlen(s);
	int u=0;
	for(int i=0;i<l;i++)
	{
		int temp=s[i]-'a';
		if(!c[u][temp])
			return false;
		u=c[u][temp];
	}
	return v[u];
}
int main()
{
	int cnt=0;
	init();
//	freopen("in.txt","r",stdin);
//	freopen("out.txt","w",stdout);
	while(scanf("%s",st[cnt])!=EOF)
	{
		insert(st[cnt]);
		cnt++;
	}
	for(int i=0;i<cnt;i++)
	{
		int l=strlen(st[i]);
		char t1[100]={'\0'};
		char t2[100]={'\0'};
		for(int j=1;j<l-1;j++) //最后一个字母不用copy了 因为那就相当于找此整个单词 
		{
			strncpy(t1,st[i],j);
			strncpy(t2,st[i]+j,l-j+1); //记得把\0也copy过去。 
			if(search(t1)&&search(t2))
			{
			
				printf("%s\n",st[i]);
				break;
			}
		}
	}
	return 0;
}


你可能感兴趣的:(HDOJ Hat’s Words 1247【经典字典树】)