您的位置:首页 > 其它

hdu1247 hat's words

2015-08-13 17:28 281 查看
Hat’s Words
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d
& %I64u
Submit Status Practice HDU
1247

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




貌似没啥区别==而且一组数组也不用del()

#include <iostream>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
typedef struct Trie_node
{
	int count;                    // 统计单词前缀出现的次数
	struct Trie_node* next[26];   // 指向各个子树的指针
	bool exist;                   // 标记该结点处是否构成单词
}TrieNode , *Trie;

TrieNode* createTrieNode()
{
	TrieNode* node = (TrieNode *)malloc(sizeof(TrieNode));
	node->count = 0;
	node->exist = false;
	memset(node->next , 0 , sizeof(node->next));    // 初始化为空指针
	return node;
}

void Trie_insert(Trie root, char* word)
{
	Trie node = root;
	char *p = word;
	int id;
	while( *p )
	{
		id = *p - 'a';
		if(node->next[id] == NULL)
		{
			node->next[id] = createTrieNode();
		}
		node = node->next[id];  // 每插入一步,相当于有一个新串经过,指针向下移动
		++p;
		node->count += 1;      // 这行代码用于统计每个单词前缀出现的次数(也包括统计每个单词出现的次数)
	}
	node->exist = true;        // 单词结束的地方标记此处可以构成一个单词
}

bool Trie_search(Trie root, char* word)
{
	Trie node = root;
	char *p = word;
	int id;
	while( *p )
	{
		id = *p - 'a';
		node = node->next[id];
		++p;
		if(node == NULL)
			return 0;
	}
	if(node->exist)          // 查找成功
        return 1;
    return 0;
}
char s[50000][100];
int main()
{
   // freopen("cin.txt","r",stdin);
    int i=0;
    Trie root = createTrieNode();
    while(scanf("%s",s[i])!=EOF)
    {
        Trie_insert(root , s[i++]);
    }
    for(int k=0;k<i;k++)
    {
        for(int j=1;j<strlen(s[k])-1;j++)
        {
            char s1[100],s2[100];
            for(int jj=0;jj<j;jj++)
              s1[jj]=s[k][jj];
            s1[j]='\0';
            strcpy(s2,s[k]+j);
            if(Trie_search(root,s1)&&Trie_search(root,s2))
            {
                printf("%s\n",s[k]);
                break;
            }
        }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: