【题目链接】click here~~
【题目大意】A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary. ,找出由两个子字符串组成的字符串。
【解题思路】字典树
#include <bits/stdc++.h>
using namespace std;
const int N=5*1e4+100;
const int MOD=998244353;
#pragma comment(linker,"/STACK:102400000,102400000")
int n,m,k,tot;
char word[N][27];
typedef long long LL;
struct dictree
{
int count;
bool ok;
dictree *tree[27];
dictree()
{
ok=false;
memset(tree,0,sizeof(tree));
}
};
void insert(dictree *head,char str[])
{
dictree *p=head;
int i=0;
while(str[i])
{
int k=(int)(str[i++]-'a');
if(p->tree[k]==NULL) p->tree[k]=new dictree();
p=p->tree[k];
}
p->ok=true;
}
bool search(dictree *head,char str[])
{
int i=0,top=0,num[N];
dictree *p=head;
while(str[i])
{
int k=(int)str[i++]-'a';
if(p->tree[k]==NULL) return false;
p=p->tree[k];
if(p->ok&&str[i]) num[top++]=i;
}
while(top)
{
bool okk=true;
i=num[--top];
p=head;
while(str[i])
{
int k=(int)str[i++]-'a';
if(p->tree[k]==NULL)
{
okk=false;
break;
}
p=p->tree[k];
}
if(okk&&p->ok) return true;
}
return false;
}
int main()
{
int len=0;
dictree *head=new dictree();
while(gets(word[len]))
{
insert(head,word[len]);
len++;
}
for(int i=0; i<len; ++i)
{
if(search(head,word[i]))
printf("%s\n",word[i]);
}
return 0;
}
</span>
set容器:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str;
set<string>sa,sb;
while(cin>>str) sa.insert(str);
set<string>::iterator be=sa.begin(),en=sa.end(),op,opp;
for(; be!=en; be++)
{
int Count=be->size();
for(op=be,op++; op!=en; op++)
{
if(be->compare(op->substr(0,Count))==0)
{
if(sa.count(op->substr(Count,op->size()-Count))) sb.insert(*op);
}
else break;
}
}
for(opp=sb.begin(); opp!=sb.end(); opp++)
cout<<*opp<<endl;
return 0;
}</span>原文地址:http://blog.csdn.net/u013050857/article/details/46559757