题意:给定一排字符串组成一个字典,求在字典中自否存在由字典中另外两个字符串组成的字符串。
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string box[50001];
struct Trie
{
bool end;
Trie* next[26];
Trie() : end(false)
{
memset(next, 0, sizeof(next));
}
};
void insert(Trie* root, string& line)
{
Trie* p = root;
int len = line.length(), n;
for (int i = 0; i < len; ++i)
{
n = line[i] - 'a';
if (p->next[n] == NULL)
p->next[n] = new Trie;
p = p->next[n];
}
p->end = true;
}
bool search(Trie* root, string& line)
{
bool flag;
int len = line.length(), n;
Trie *p = root, *q;
for (int i = 1; i < len; ++i)
{
p = p->next[line[i-1] - 'a'];
if (p->end == true)
{
q = root;
flag = true;
for (int j = i; j < len; ++j)
{
n = line[j] - 'a';
if (q->next[n] == NULL)
{
flag = false;
break;
}
q = q->next[n];
}
if (q->end == 1 && flag)
return true;
}
}
return false;
}
int main()
{
Trie* root = new Trie;
int i = 0;
while (getline(cin, box[i]))
insert(root, box[i++]);
for (int j = 0; j < i; ++j)
{
if (search(root, box[j]))
cout << box[j] << endl;
}
}