Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11388 Accepted Submission(s): 4071
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.
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.
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
事先我把两个单词拼接起来,看看拼成的单词是否存在于字典树,结果把5e4看成了5e3,以为二重循环能过的,
正解是遍历单词,然后看他能否分成两个单词都存在于字典树中,虽然对于每个单词的拆分都要试好多次,但是单词长度毕竟有限,比我原来的做法要快得多。
复习了一下strncpy的用法,其实我写的代码中,for里面并不是每次都要用strncpy,如果用回溯法,应该可以节约时间成本。
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<climits>
#include<queue>
#include<vector>
#include<map>
#include<sstream>
#include<set>
#include<stack>
#include<cctype>
#include<utility>
#pragma comment(linker, "/STACK:102400000,102400000")
#define PI (4.0*atan(1.0))
#define eps 1e-10
#define sqr(x) ((x)*(x))
#define FOR0(i,n) for(int i=0 ;i<(n) ;i++)
#define FOR1(i,n) for(int i=1 ;i<=(n) ;i++)
#define FORD(i,n) for(int i=(n) ;i>=0 ;i--)
#define lson ind<<1,le,mid
#define rson ind<<1|1,mid+1,ri
#define MID int mid=(le+ri)>>1
#define zero(x)((x>0? x:-x)<1e-15)
#define mk make_pair
#define _f first
#define _s second
using namespace std;
//const int INF= ;
typedef long long ll;
//const ll inf =1000000000000000;//1e15;
//ifstream fin("input.txt");
//ofstream fout("output.txt");
//fin.close();
//fout.close();
//freopen("a.in","r",stdin);
//freopen("a.out","w",stdout);
const int INF =0x3f3f3f3f;
const int maxn= 50000+20 ;
const int Len=150;
const int N=26;
//const int maxm= ;
char word[maxn][Len];
char tmp[Len];
int root,cnt,n;
struct Node
{
int nex[N];
bool has;
void init()
{
for(int i=0;i<N;i++)
nex[i]=0;
has=0;
}
}node[maxn*Len];
int newnode()
{
node[++cnt].init();
return cnt;
}
void insert(char *tmp)
{
int s=root;
for(int i=0;tmp[i];i++)
{
int x=tmp[i]-'a';
if(! node[s].nex[x] ) node[s].nex[x]=newnode();
s=node[s].nex[x];
}
node[s].has=1;
}
bool search(char * tmp)
{
int s=root;
for(int i=0;tmp[i] ;i++)
{
int x=tmp[i]-'a';
if(!node[s].nex[x]) return false;
s=node[s].nex[x];
}
return node[s].has;
}
int main()
{
root=cnt=1;
node[root].init();
n=0;
while(~scanf("%s",&word[++n]) )
{
insert(word[n]);
}
n--;
for(int i=1;i<=n;i++)
{
int len=strlen(word[i]);
for(int ed=0;ed<len-1;ed++)
{
strncpy(tmp,word[i],ed+1);
tmp[ed+1]='\0';
if(search(tmp)&&search(word[i]+ed+1) )
{
printf("%s\n",word[i]);
break;
}
}
}
return 0;
}