字典树模拟题,问是否会有字符串是另一字符串的前缀,有输出NO,没有输出YES。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#define mem(a) memset(a, 0, sizeof(a))
#define maxn 10
using namespace std;
char ch[maxn];
bool flag;
struct trie_tree
{
bool flag;
bool flag2;
trie_tree *next[maxn];
};
struct trie_tree *root;
void add()
{
int len, i = 0, a, j;
struct trie_tree *q;
q = root;
len = strlen(ch);
while(i < len)
{
a = ch[i] - 48;
if(q->next[a] == NULL)
{
q->flag2 = 1;
q->next[a] = (struct trie_tree *)malloc(sizeof(trie_tree));
q->next[a]->flag = 0;
q->next[a]->flag2 = 0;
for(j = 0;j <= 9;j++)
q->next[a]->next[j] = NULL;
if(i == (len - 1))
{
q->next[a]->flag = 1;
}
q = q->next[a];
}
else
{
if(i == (len - 1))
{
if(q->next[a]->flag2 == 1)
{
flag = 1;
break;
}
}
if(q->next[a]->flag)
{
flag = 1;
break;
}
q = q->next[a];
}
i++;
}
return;
}
void deal(struct trie_tree *q)
{
int i;
for(i = 0;i <= 9;i++)
{
if(q->next[i] != NULL)
{
deal(q->next[i]);
}
}
free(q);
return;
}
int main(int argc, char *argv[])
{
int t, n, j, o = 0;
scanf("%d", &t);
mem(ch);
while(t--)
{
root = (struct trie_tree *)malloc(sizeof(trie_tree));
for(j = 0;j <= 9;j++)
root->next[j] = NULL;
scanf("%d", &n);
flag = 0;
while(n--)
{
scanf("%s", ch);
if(flag)
{
while(n--)
{
scanf("%s", ch);
}
mem(ch);
break;
}
add();
mem(ch);
}
if(!flag)
printf("Case %d: YES\n", ++o);
else
printf("Case %d: NO\n", ++o);
deal(root);
}
return 0;
}