Hat’s Words Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Problem Description A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the 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.
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: 1075 1298 1800 2846 1305
|
给你多个单词,问你其中两个单词是否可以组成字典中的单词。
分析:直接把每一段字符暴力拆开就行,但有许多细节,坑了我好久
#include<cstdio>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<functional>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<numeric>
#include<cctype>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<list>
#include<set>
#include<map>
using namespace std;
#define N 300000+5
#define MAX 26
typedef long long ll;
const int maxnode=50000+100;//预计字典树最大节点数目
const int sigma_size=27; //每个节点的最多儿子数
struct Trie
{
int ch[maxnode][sigma_size];//ch[i][j]==k表示第i个节点的第j个儿子是节点k
int val[maxnode];//val[i]==x表示第i个节点的权值为x
int sz;//字典树一共有sz个节点,从0到sz-1标号
//初始化
void clear()
{
sz=1;
memset(ch,0,sizeof(ch));//ch值为0表示没有儿子
memset(val,0,sizeof(val));
}
//在字典树中插入单词s,但是如果已经存在s单词会重复插入且覆盖权值
//所以insert前需要判断一下是否已经存在s单词了
void insert(string s)
{
int u=0,n=s.length();
for(int i=0;i<n;i++)///建立字典树
{
int id=s[i]-'a';
if(ch[u][id]==0)//无该儿子
{
ch[u][id]=sz;
memset(ch[sz],0,sizeof(ch[sz]));
sz++;
}
u=ch[u][id];
}
val[u]=1;
}
//在字典树中查找单词s
int find(string s)
{
int n=s.length(),u=0;
for(int i=0;i<n;i++)
{
int id=s[i]-'a';
if(ch[u][id]==0)
return 0;
u=ch[u][id];
}
return val[u];
}
};
vector<string> v;
Trie trie;
int main()
{
trie.clear();
char s[100];
while(gets(s))
{
//if(strlen(s)==0) break;
v.push_back(s);
trie.insert(s);
}
for(int i=0;i<v.size();i++)
{
for(int j=1;j<v[i].size();j++)
{
string s1=v[i].substr(0,j);
string s2=v[i].substr(j);
//cout<<s1<<" "<<s2<<endl;
if(trie.find(s1)&&trie.find(s2))
{
cout<<v[i]<<endl;
break; //这个不写会错误
}
}
}
return 0;
}