Zoj 1808 Immediate Decodability(字符串_字典树)

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1808

 

题目大意:给定若干个字符串,问这些字符串中是否出现某个串是另外一个串的子串。

 

解题思路:用字典树求解,先建树,再对每个串进行查询,看在遍历完这个串之后是否会有子节点,有则说明它是其他串的子串。


测试数据:

01

10
0010
0000

9


01
10
010
0000

9


代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1000


struct node {

	int flag;
	node *next[2];
}*root;
int flag;
char str[MAX][20];


node *CreateNode() {

	node *p;
	p = (node *) malloc (sizeof(node));
	p->flag = 0;
	p->next[0] = p->next[1] = NULL;
	return p;
}
void Release(node *p) {

	if (p->next[0] != NULL)
		Release(p->next[0]);
	if (p->next[1] != NULL)
		Release(p->next[1]);
	free(p);
}
void Insert(char *str) {

	int i = 0,k;
	node *p = root;


	while (str[i]) {

		k = str[i++] - '0';
		if (p->next[k] == NULL)
			p->next[k] = CreateNode();
		p = p->next[k];
	}
	p->flag = 1;
}
void Query(char *str) {

	int i = 0,k;
	node *p = root;


	while (str[i]) {

		k = str[i++] - '0';
		p = p->next[k];
	}
	if (p->next[0] != NULL || p->next[1] != NULL)
		flag = 1;
}


int main()
{
	int i,cas = 0,tot;


	while (scanf("%s",str[0]) != EOF) {

		if (str[0][0] == '9') {
			
			printf("Set %d is immediately decodable\n",++cas);
			continue;
		}
		tot = flag = 0;
		root = CreateNode();
		Insert(str[0]);
		while (scanf("%s",str[++tot]),str[tot][0] != '9')
			Insert(str[tot]);


		for (i = 0; i < tot; ++i)
			if (flag == 0) Query(str[i]);
		if (flag == 0) 
			printf("Set %d is immediately decodable\n",++cas);
		else 
			printf("Set %d is not immediately decodable\n",++cas);
		Release(root);
	}
}

本文ZeroClock原创,但可以转载,因为我们是兄弟。

你可能感兴趣的:(struct,测试,null,query,insert)