大意:给你一段单词,若给定的单词中有一个是另外两个单词合并而成的话,则输出。
思路:Trie+枚举,每输入一个单词,插入进Trie中,然后枚举它所有的前缀数,然后通过函数strncpy函数确定剩余的字母组成的单词,然后通过Trie的基本查找来确定是否包含两个单词。
CODE:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
struct Trie
{
Trie *next[26];
int value;
Trie()
{
for(int i = 0; i < 26; i++)
next[i] = 0;
value = 0;
}
};
char save[50001][1001];
void insert(Trie *&root, char *s)
{
int i = 0, branch = 0;
Trie *p = root;
if(!p)
{
p = new Trie();
root = p;
}
while(s[i])
{
branch = s[i]-'a';
if(!p->next[branch]) p->next[branch] = new Trie();
p = p->next[branch];
i++;
}
p->value = 1;
}
int find(Trie *root, char *s)
{
int i = 0, branch = 0;
Trie *p = root;
if(!p) return 0;
while(s[i])
{
branch = s[i]-'a';
if(!p->next[branch]) return 0;
p = p->next[branch];
i++;
}
if(p->value) return 1;
return 0;
}
int main()
{
int tot = 0;
Trie *root = NULL;
while(~scanf("%s", save[tot]))
{
insert(root, save[tot]);
tot++;
}
for(int i = 0; i < tot; i++)
{
for(int j = 0; j < strlen(save[i]); j++)
{
char temp1[101] = {'\0'};
char temp2[101] = {'\0'}; //strncpy用法的特殊性
strncpy(temp1, save[i], j);
strncpy(temp2, save[i]+j, strlen(save[i])-j); //求后半部分单词
if(find(root, temp1) && find(root, temp2))
{
printf("%s\n", save[i]);
break; //可能有重复的,所以必须退出。
}
}
}
return 0;
}
#include <cstring>
#include <cstdio>
using namespace std;
struct Trie
{
Trie *next[26];
int value;
Trie()
{
for(int i = 0; i < 26; i++)
next[i] = 0;
value = 0;
}
};
char save[50001][1001];
void insert(Trie *&root, char *s)
{
int i = 0, branch = 0;
Trie *p = root;
if(!p)
{
p = new Trie();
root = p;
}
while(s[i])
{
branch = s[i]-'a';
if(!p->next[branch]) p->next[branch] = new Trie();
p = p->next[branch];
i++;
}
p->value = 1;
}
int find(Trie *root, char *s)
{
int i = 0, branch = 0;
Trie *p = root;
if(!p) return 0;
while(s[i])
{
branch = s[i]-'a';
if(!p->next[branch]) return 0;
p = p->next[branch];
i++;
}
if(p->value) return 1;
return 0;
}
int main()
{
int tot = 0;
Trie *root = NULL;
while(~scanf("%s", save[tot]))
{
insert(root, save[tot]);
tot++;
}
for(int i = 0; i < tot; i++)
{
for(int j = 0; j < strlen(save[i]); j++)
{
char temp1[101] = {'\0'};
char temp2[101] = {'\0'}; //strncpy用法的特殊性
strncpy(temp1, save[i], j);
strncpy(temp2, save[i]+j, strlen(save[i])-j); //求后半部分单词
if(find(root, temp1) && find(root, temp2))
{
printf("%s\n", save[i]);
break; //可能有重复的,所以必须退出。
}
}
}
return 0;
}