Light OJ 1129 Consistency Checker

24 篇文章 0 订阅
21 篇文章 0 订阅
  字典树模拟题,问是否会有字符串是另一字符串的前缀,有输出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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值