HDU_1247 Hat’s Words(Trie 树)
Trie水题,将每个单词插入Trie树,然后暴力拆分每个单词到树中查找匹配即可!有几个要注意的细节,代码注释中都标上了。
My Code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX = 50007;
struct node
{
int flag;
node * next[26];
};
char dis[MAX][30];
node * newnode()
{
int i;
node * p = new node;
p->flag = 0;
for(i = 0; i < 26; i++)
p->next[i] = NULL;
return p;
}
void insert(node * root, char *s)
{
node * p = root;
int i, len = strlen(s), t;
for(i = 0; i < len; i++)
{
t = s[i] - 'a';
if(p->next[t] == NULL)
p->next[t] = newnode();
p = p->next[t];
}
p->flag = 1;
}
int search(node * root, char *s)
{
node * p = root;
int i, t, len = strlen(s);
for(i = 0; i < len; i++)
{
t = s[i] - 'a';
if(p->next[t] == NULL)
return 0;
p = p->next[t];
}
if(p->flag)
return 1;
return 0;
}
int main()
{
//freopen("data.in", "r", stdin);
int n = 0, i, j, k;
char s1[30], s2[30];
node * root = newnode();
while(scanf("%s", dis[n]) != EOF)
{
insert(root, dis[n]);
n++;
}
for(i = 0; i < n; i++) //拆分
{
int len = strlen(dis[i]);
memset(s1, 0, sizeof(s1)); //每次置空字符串数组,否则会段错误(这里就是数组溢出)
for(j = 0; j < len-1; j++)
{
s1[j] = dis[i][j];
memset(s2, 0, sizeof(s2)); //同理
for(k = j+1; k < len; k++)
{
s2[k-j-1] = dis[i][k];
}
if(search(root, s1) && search(root, s2))
{
puts(dis[i]);
break;
}
}
}
return 0;
}