杭电hdu 1247 hat's words

http://acm.hdu.edu.cn/showproblem.php?pid=1247

字典树的又一简单题,简单介绍见本目录中的另一个题。

//字典树的应用问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 51

char words[50001][MAX];//缓存所有输入的单词

typedef struct _node
{
	bool end;
	_node * next[26];
}node;

static node root = {0, {NULL}};

void insert(char * word, int len)//向字典树中插入数据
{
	node *cur, *newnode;
	int i;
	cur = &root;
	for(i = 0; i < len; ++ i){
		if(cur->next[word[i]-'a'] == NULL){
			newnode = (node*)malloc(sizeof(node));
			memset(newnode, 0, sizeof(node));
			cur->next[word[i]-'a'] = newnode;
		}
		cur = cur->next[word[i]-'a'];
	}
	cur->end = true;
}

bool find(char * word, int len)//查找字典树
{
	node *cur = &root;
	int i;
	for(i = 0; i < len; ++ i){
		if(cur->next[word[i]-'a'] == NULL)return false;
		cur = cur->next[word[i]-'a'];
	}
	if(!cur->end)return false;
	return true;
}

int main()
{
//	freopen("input.txt","r", stdin);
	char left[MAX], right[MAX];
	int cnt = 0, i, j;
	while(scanf("%s", words[cnt])!=EOF){
		insert(words[cnt ++], strlen(words[cnt]));//为什么cnt++不能放在后面呢?
	}

	for(i = 0; i < cnt; ++ i){
		int len = strlen(words[i]);
		for(j = 1; j < len; ++ j){
			strcpy(left, words[i]);
			left[j] = '\0';
			strcpy(right, words[i]+j);
			if(find(left, j) && find(right, len-j)){
				printf("%s\n", words[i]);
				break;
			}
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值