http://acm.hdu.edu.cn/showproblem.php?pid=1247
Total Submission(s): 8801 Accepted Submission(s): 3156
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 8801 Accepted Submission(s): 3156
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
Ignatius.L
题目大意就是将一个单词分解成两个单词,判断这两个单词是否在输入的这些字符串当中。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>
#include <stack>
#define maxn 50000+5
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 90001
#define PI 3.141592657
#define INF 1<<30
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
bool cmp(int a,int b)
{
return a>b;
}
struct node
{
int next[27];
int v;
void init()
{
v=0;
memset(next,-1,sizeof(next));
}
};
node L[1000500];
string s[maxn];
int tot=0;
void add(string s)
{
int len=s.size();
int now=0;
for(int i=0;i<len;i++)
{
int t=s[i]-'a';
int x=L[now].next[t];//不存在为-1
if(x==-1)
{
x=++tot;
L[x].init();
L[now].next[t]=x;
}
now=x;
}
L[now].v++;
}
int query(string s)//查询字符串是否存在
{
int len=s.size();
int now=0;
for(int i=0;i<len;i++)
{
int t=s[i]-'a';
int x=L[now].next[t];
if(x==-1)return 0;
now=x;
}
if(L[now].v>0)return 1;
return 0;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
int n=0;
L[0].init();//一定要记住初始化
L[0].v=0;
while(cin>>s[n])
{
add(s[n]),n++;
}
for(int i=0;i<n;i++)
{
for(int j=1;j<s[i].size()-1;j++)
{
string s1(s[i],0,j); //表示把s[i]中从下标0开始连续的j个字符赋给s1
string s2(s[i],j,s[i].size()-j);
//string s1=s[i].substr(0,j);
//string s2=s[i].substr(j,l-j);
//cout<<"KK"<<s1<<" "<<s2<<endl;
if(query(s1)&&query(s2))
{
cout<<s[i]<<endl;
break;
}
}
}
return 0;
}