Hat’s Words

链接:http://acm.hust.edu.cn/vjudge/problem/18360/origin

题目:A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.

题意:给出一个单词表,把所有可以用另外两个单词链接起来表示的单词打印出来。

分析:多维互相匹配,字典树的特征。存储用模板就好,查询的时候要下点功夫。对于这道题,某个单词可能不仅仅能由两个单词组成,比如。。。瞎编一个ab,abcd,cd,c,d。abcd可以是两个也可以是三个单词组成。解决办法是查找的时候,把每个分割点都记录下来,如果分割点到结尾可以组成一个单词,那么就可以被两个单词组成。问题得解。

题解:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return 0
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false)
using namespace std;

struct Node
{
	Node() :is(false), count(0) { memset(next, 0, sizeof next); }
	bool is;
	int count;
	int next[26];
}no[100000];

string s[50010];
int root = 0;
int rl = 0;

void insert(string &s)
{
	int len = s.size();
	int p = root;
	for (int i = 0; i < len; i++)
	{
		int id = s[i] - 'a';
		if (!(no[p].next[id]))
			no[p].next[id] = ++rl;
		p = no[p].next[id];
	}
	no[p].is = true;
}

bool find(string &s)
{
	int len = s.size();
	int sta[1000];
	int p = root;
	int sl = 0;
	for (int i = 0; i < len; i++)
	{
		int id = s[i] - 'a';
		p = no[p].next[id];
		if (no[p].is)
			sta[sl++] = i+1;
	}
	while (sl)
	{
		bool flag = true;
		int i = sta[--sl];
		p = root;
		while (i<len)
		{
			int id = s[i++] - 'a';
			if (!(no[p].next[id]))
			{
				flag = false;
				break;
			}
			p = no[p].next[id];
		}
		if (flag&&no[p].is)
			return true;
	}
	return false;
}

int main()
{
	//fr;
	detie;
	int i = 0;
	//root = new Node;
	while (cin>>s[i])
	{
		insert(s[i]);
		i++;
	}
	int j = 0;
	while (j<i)
	{
		if (find(s[j]))
			cout << s[j] << endl;
		j++;
	}
	rt;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值