HDU - 1247 -- Hat’s Words【字典树】

Hat’s Words

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

题意

查找所有字符串中,能够恰好满足 c = a + b,也就是一个字符串能用另外两个字符串表示。

思路

暴力枚举所有拆分可能,如果找到字符串的前半段和后半段都在字典中,就满足题意条件。

AC代码

#include
#include
#include
#include
#define IOS  std::ios::sync_with_stdio(false)
using namespace std;
const int maxn = 5e4 + 5;
int tree[maxn*100][26];//i号结点有没有j字符的边。如果有存的是这个端点的编号 
bool vis[maxn*100];
int k = 1;//从一号结点开始编号 
string str[maxn];
void insert(string w, int len){
	int u = 0;
	for (int i = 0; i < len; ++i){
		int v = w[i] - 'a';
		if (!tree[u][v]){
			tree[u][v] = k++;
		}
		u = tree[u][v];
	}
	vis[u] = true;
}
bool query(string w, int len){
	int i, cnt = 0, u = 0;
	for (i = 0; i < len; ++i){
		int v = w[i] - 'a';
		if (!tree[u][v])	return false;
		u = tree[u][v];
	}
	return vis[u];
}
void solve(){
	int cnt = 0;
	while (cin >> str[cnt]){
		insert(str[cnt], str[cnt].size());
		cnt++;
	}
	for (int i = 0; i < cnt; ++i){
		int len = str[i].size();
		string s1, s2;
		for (int j = 0; j < len; ++j){
			s1 = str[i].substr(0,j);
			s2 = str[i].substr(j);
			bool flag1 = query(s1, s1.size());
			bool flag2 = query(s2, s2.size());
			if (flag1 && flag2){
				cout << str[i] << endl;
				//坑点,一个单词可能出现多对单词的拼写 
				break;
			}
		}
	}
}
int main(){
	IOS;
	solve();
	return 0;
} 
/**
a
aa
aab
aabc
ab
aba
**/

你可能感兴趣的:(#,字典树,马拉车,kmp)