您的位置:首页 > 其它

字典树

2015-10-06 22:27 232 查看
初步学了下字典树,,,有好多地方都还是搞不清楚为什么这样写,,,不过可以基本的套用模板。套用模板做了这个题:hdu1247http://acm.hdu.edu.cn/showproblem.php?pid=1247

Hat’s WordsTime Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11265    Accepted Submission(s): 4020Problem DescriptionA 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. InputStandard 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. OutputYour output should contain all the hat’s words, one per line, in alphabetical order. Sample Input
aahathathatwordhzieeword Sample Output
ahathatword题意就是:给出一些单词,找出其中能由其他两个单词连接而成的单词。“ahat” = “a” + “hat”。#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <string>#include <algorithm>#include <queue>using namespace std;const int MAXN = 1000000;char s[50005][101];struct Node{int flag;int cnt;struct Node * next[26];} tree[MAXN];int t = 0;struct Node *creat(){struct Node *p;p = &tree[t ++];p->cnt = 1;p->flag = 0;for(int i = 0; i < 26; i++)p->next[i] = NULL;return p;}void Insert(struct Node **root,char *ss){struct Node *p;if(!(p = *root))p = *root = creat();int i = 0,k;while(ss[i]){k = ss[i ++] - 'a';if(p->next[k])p->next[k]->cnt ++;else p->next[k] = creat();p = p->next[k];}p->flag = 1;}int Search(struct Node **root,char *ss){struct Node *p;if(!(p = *root))return 0;int i = 0,k;while(ss[i]){k = ss[i++] - 'a';if(!(p->next[k]))return 0;p = p->next[k];}return p->flag;}int main(){//    freopen("in.txt","r",stdin);char s1[101],s2[101];struct Node *root = NULL;int i = 0;while(~scanf("%s",s[i])){Insert(&root,s[i]);i ++;}for(int j = 0;j < i;j++){memset(s1,0,sizeof(s1));int l = strlen(s[j]);for(int k = 0;k < l;k++){s1[k] = s[j][k];if(Search(&root,s1)){memset(s2,0,sizeof(s2));for(int q = k + 1;q < l;q ++){s2[q - k - 1] = s[j][q];}if(Search(&root,s2)){puts(s[j]);break;}}}}return 0;}字典树:http://www.cnblogs.com/pony1993/archive/2012/07/18/2596730.html
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: