Light OJ 1129 Consistency Checker

  字典樹模擬題,問是否會有字符串是另一字符串的前綴,有輸出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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章