HDU1247(Hat’s Words)

  • 时间:
  • 来源:互联网
  • 文章标签:
Hat’s Words

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

思路

给定很多单词,问是否存在一个单词是由给定的两个单词组成的。首先对给定的单词建立一棵字典树,给单词末尾标记一下,然后暴力枚举每个单词的左半边和右半边。如果两边都能找到说明这个单词是可以由两个单词组合而成,还是挺简单的一道题。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 100005;
int trie[maxn][26];
char str[50005][40];
bool f[maxn];
int cnt = 0;
void insert_s(char *s)
{
	int root = 0;
	int n = strlen(s);
	for(int i = 0;i < n;i++){
		int k = s[i] - 'a';
		if(!trie[root][k]){
			trie[root][k] = ++cnt;
		}
		root = trie[root][k];
	}
	f[root] = true;
} 
bool find_s(char *s,int x,int y)
{
	int root = 0;
	for(int i = x;i < y;i++){
		int k = s[i] - 'a';
		if(!trie[root][k]){
			return false;
		}
		root = trie[root][k];
	}
	return f[root];
}
int main()
{
	memset(trie,0,sizeof(trie));
	memset(f,false,sizeof(f));
	int n = 0;cnt = 0;
	while(~scanf("%s",str[n])){
		insert_s(str[n]);n++;
	}
	for(int i = 0;i < n;i++){
		int len = strlen(str[i]);
		int ans = 0;
		for(int j = 1;j < len;j++){
			bool a = find_s(str[i],0,j);
			bool b = find_s(str[i],j,len);
			if(a && b){
				ans = 1;
				break;
			}
		}
		if(ans == 1)	printf("%s\n",str[i]); 
	}
	return 0;
}

愿你走出半生,归来仍是少年~

本文链接http://www.taodudu.cc/news/show-82818.html