HDU1247-Hat’s Words

题目链接

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18278    Accepted Submission(s): 6491


 

Problem Description

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.

 

 

Input

Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.

 

 

Output

Your output should contain all the hat’s words, one per line, in alphabetical order.

 

 

Sample Input

 

a ahat hat hatword hziee word

 

 

Sample Output

 

ahat hatword

题目大意:给出的字符串任意两个组合,是否能组合出原来已经存在的字符串,可以的话,组合出来的就是讨厌的。

思路:字典树,然后暴力把每个单词分成两部分,都能找到,就是讨厌的

AC代码:

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

char s[50010][100];
typedef struct Trie_Node {
	struct Trie_Node* next[26];
	bool isword;
	int num; 
	Trie_Node() {//初始化 
		for(int i = 0; i < 26; i++) {
			next[i] = NULL;
		}
		isword = false;//单词结束标志 
		num = 0;//到达该处的字符串数量 
	}
}trie; 

void insert(trie* root, char* s) {
	trie* p = root;
	int i = 0;
	while(s[i] != '\0') {
		if(p->next[s[i]-'a'] == NULL) {//为空,就开,然后指向它 
			trie* temp = new trie();
			p->next[s[i]-'a'] = temp;
		}
		p = p->next[s[i]-'a'];//继续跑 
		i++;
		p->num++;//到达该处的字符串++ 
	}
	p->isword = true;//单词结束 
}

bool search(trie* root, char* s) {
	trie* p = root;
	for(int i = 0; s[i] != '\0'; i++) { 
		if(p->next[s[i]-'a'] == NULL)//找不到该单词, 
			return false;
		p = p->next[s[i]-'a'];
	}
	return p->isword; 
}

void del(trie *root) {
	for(int i = 0; i < 26; i++) {
		if(root->next[i] != NULL)
			del(root->next[i]);
	}
	free(root);
} 

int main() {
	int cnt = 0;
	trie* root = new trie();
	while(~scanf("%s", s[cnt])) {//输入巧妙 
		insert(root, s[cnt++]);
	}
	for(int i = 0; i < cnt; i++) {
		int len = strlen(s[i]);
		for(int j = 1; j < len-1; j++) {//暴力分解 
			char temp1[50] = {'\0'};
			char temp2[50] = {'\0'};
			strncpy(temp1, s[i], j);//从0 到j 
			strncpy(temp2, s[i]+j, len-j);//从j+1 到 结束 
			if(search(root, temp1) && search(root, temp2)) {
				printf("%s\n", s[i]);
				break;
			}
		}
	}
	del(root);
} 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值