题意:给定一个字典,要你判断其中的任意两个单词是否可以组成另一个单词。
解法:trie树,记录所有的单词,然后再对每个档次枚举分隔点。神奇的是我释放内存就RE,不释放就A了。没搞懂。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 50005
#define KIND 26
struct TreeNode
{
int count;
TreeNode *next[KIND];
TreeNode()
{
count = 0;
memset(next, 0, sizeof(next));
}
}*root;
char data[N][105], data1[105], data2[105];
void Insert(char *s)
{
TreeNode *r = root;
for(; *s; s++)
{
int t = (*s) - 'a';
if(NULL == r->next[t])
{
r->next[t] = new TreeNode();
}
r = r->next[t];
}
r->count = 1;
}
bool Find(char *s)
{
int count = 0;
TreeNode *r = root;
for(; *s; s++)
{
int t = (*s) - 'a';
if(r->next[t] == NULL) return false;
r = r->next[t];
}
if(r->count) return true;
return false;
}
void Release(TreeNode *p)
{
for(int i = 0; i < KIND; i++)
{
if(p->next[i]) Release(p);
}
delete p;
}
int main()
{
int n = 0;
root = new TreeNode();
while(scanf("%s", data[n]) != EOF)
{
Insert(data[n]);
n++;
}
for(int i = 0; i < n; i++)
{
int l = strlen(data[i]);
for(int j = 1; j < l; j++)
{
int k;
for(k = 0; k < j; k++)
data1[k] = data[i][k];
data1[k] = '\0';
for(k = j; k < l; k++)
data2[k - j] = data[i][k];
data2[k - j] = '\0';
// strncpy(data1, data[i], j);
// strncpy(data2, data[i] + j, l - j + 1);
// puts(data1);puts(data2);
if(Find(data1) && Find(data2))
{
puts(data[i]);
break;
}
}
}
//Release(root);
return 0;
}