zoukankan      html  css  js  c++  java
  • hdu 1247 Hat’s Words 字典树

    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
     
             字典树:以给的每个单词建树。然后给每个单词分成两半查找,如果两半都在树中查找到了,就输出者个单词。
     
         
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    char s[50005][50];
    struct f
    {
        int next[30];
        int v;
        void ff()
        {
            memset(next,-1,sizeof(next));
            v=0;
        }
    };f tree[1000000];
    int cut=0;
    void buld(char *s1)
    {
        int i,k=0,su;
        for (i=0;s1[i]!='';i++)
        {
            su=s1[i]-'a';
            if (tree[k].next[su]==-1)
            {
                cut++;
                tree[k].next[su]=cut;
                tree[cut].ff();
            }
            k=tree[k].next[su];
        }
        tree[k].v=1;
        return ;
    }
    int find(char *s1)
    {
        int i,k=0,su,len;
        len=strlen(s1);
        for (i=0;i<len;i++)
        {
            su=s1[i]-'a';
            if (tree[k].next[su]==-1) break;
            k=tree[k].next[su];
        }
        if (i==len&&tree[k].v) return 1;
        return 0;
    }
    int main()
    {
         int p=0,i,j,len,k,d;
         char sl[50],sr[50];
         tree[cut].ff();
         while (~scanf("%s",s[p]))
         {
             buld(s[p]);
             p++;
         }
         for (i=0;i<p;i++)
         {
             len=strlen(s[i]);
             for (j=0;j<len;j++)
             {
                 memset(sr,'',sizeof(sr));
                 memset(sl,'',sizeof(sl));
                for (k=0;k<j;k++) sl[k]=s[i][k];
                sl[j]='';
                for (k=j,d=0;k<len;k++,d++) sr[d]=s[i][k];
                sr[len]='';
                 if (find(sl)&&find(sr))
                 {
                     printf("%s
    ",s[i]);
                     break;
                 }
             }
         }
         return 0;
    }
    
  • 相关阅读:
    为什么处理有序数组比无序数组快?
    LeetCode:Longest Common Prefix
    LeetCode:Container With Most Water,Trapping Rain Water
    LeetCode:Substring with Concatenation of All Words (summarize)
    LeetCode:Pow(x, n)
    LeetCode:Combination Sum I II
    LeetCode:N-Queens I II(n皇后问题)
    LeetCode:Valid Sudoku,Sudoku Solver(数独游戏)
    LeetCode:Divide Two Integers
    LeetCode:Reverse Nodes in k-Group
  • 原文地址:https://www.cnblogs.com/pblr/p/4712733.html
Copyright © 2011-2022 走看看