hdu 题目1247 Hat’s Words(字典树)

Hat’s Words

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 5   Accepted Submission(s) : 3
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
 


1.将所有单词创建字典树

2.将每个单词拆分成两个,(如单词 ahat 依次拆分成 a,hat ;  ah,at;   aha,t; )依次判断拆分的两个单词是否存在与字典树




#define N 50005
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct Tire
{
	Tire * child[26];
	bool flag;
}Tire;

Tire * root;
void insert(char * s)//创建字典树
{
	Tire *p,*q=root;
	for(int i=0;i<strlen(s);i++)	{
		if(q->child[s[i]-'a']) q = q->child[s[i]-'a'];
		else{
			p = (Tire *)malloc(sizeof(Tire));
			p->flag=0;
			for(int j=0;j<26;j++) p->child[j]=NULL;
			q->child[s[i]-'a'] = p;
			q = p;
		}
	}
	q->flag = 1;//标志为1的代表这里是某个单词的结尾
}
bool find(char *s)
{
	Tire * q=root;
	for(int i=0;i<strlen(s);i++){	
		if(q->child[s[i]-'a']) q = q->child[s[i]-'a'];
		else	return false;
	}
	if(q->flag==1) return true;//在字典树中找到该单词
	else return false;
}
int main()
{
	char s[N][20],s1[20],s2[20];
	root = (Tire *)malloc(sizeof(Tire));
	for(int i=0;i<26;i++) root->child[i]=NULL;
	
	int k=0;
	while(scanf("%s",s[k])!=EOF )
		insert(s[k++]);
	for(int i=0;i<k;i++){
		for(int j=1;j<strlen(s[i]);j++){
			for(int m=0;m<j;m++) s1[m]=s[i][m]; //将每个单词拆分成两个
			s1[j] = '\0';
			sscanf(s[i]+j,"%s",s2);

			if(find(s1)&&find(s2)) { //拆分的两个单词都存在与字典树
				puts(s[i]);	break;
			}
		}
	}
	return 0;
}



别人的STL 简单代码,没用过,不懂!!!先贴着,学过STL 以后看,这个效率不高。。

#include <iostream>
#include <string>
#include <map>
using namespace std;
map <string, int> m_v;
string str[50006];
int main() {
    int k(-1);
    while(cin >> str[++k]) {
        m_v[str[k]] = 1;
    }
    for(int i = 0; i <= k; i++) {
        int e = str[i].size()-1;
        for(int j = 1; j < e; j++) {
            string s1(str[i], 0, j);
            string s2(str[i], j);
            if(m_v[s1] == 1 && m_v[s2] == 1) {
                cout << str[i] << endl;
                break;
            }
        }
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值