POJ 1318 Word Amalgamation

题目链接:http://poj.org/problem?id=1318

看了别人的代码觉得用了set数据结构真的好神奇, 好简单


题目大意:从字典中寻找由 一些字母组成的单词

代码:字典树,排序

思路:在字典的节点上保存下存入 经过排序的

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;

struct Str
{
	char s[7];
};

struct nod
{
	int c[29];
	Str s[100];
	int cnt;
	int fl;
}p[600];
int tot = 0;
char temp[8];
int New_node(int n)
{
	memset(p[tot].c, -1, sizeof(p[tot].c));
	p[tot].cnt = 0;
	return tot ++ ;
}

bool cmp(char a, char b)
{
	return a < b ;
}

bool cmp1(Str a, Str b)
{
	return strcmp(a.s, b.s) < 0;
}

void insert(char s[])
{
	int now = 0;
	int len = strlen(s);
	strcpy(temp, s);
	sort(s, s+len);
	int i;
	for(i = 0; i < len; i ++)
	{
		int a = s[i] - 'a';
		if(p[now].c[a] == -1)
			p[now].c[a] = New_node(i+1);
		now = p[now].c[a];
	}
	strcpy(p[now].s[p[now].cnt].s, temp);
	p[now].cnt ++;
}

void find(char s[])
{
	int now = 0;
	int len = strlen(s);
	sort(s, s+len);
	int i;
	for(i = 0; i < len; i ++)
	{
		int a = s[i] - 'a';
		if(p[now].c[a] == -1)
		{
			printf("NOT A VALID WORD\n");
			return ;
		}
		now = p[now].c[a];
	}
	sort(p[now].s, p[now].s + p[now].cnt, cmp1);
	for(i = 0; i < p[now].cnt; i ++)
		printf("%s\n", p[now].s[i].s);
}

int main()
{
	int root = New_node(0);
	char s[12];
	while(scanf("%s", s))
	{
		if(s[0] == 'X')
			break;
		insert(s);
	}
	while(scanf("%s", s))
	{
		if(s[0] == 'X')
			break;
		find(s);
		printf("******\n");
	}
	return 0;
}

单词,然后把节点所有的单词排序, 用find函数搜索到节点输出单词


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值