zoukankan      html  css  js  c++  java
  • Hdu 1247 Hat's Words(Trie树)

    Hat’s Words
    Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 14083 Accepted Submission(s): 5049
    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
    Author
    戴帽子的
    Recommend
    Ignatius.L

    /*
    这题询问Trie树上是否存在一个单词,
    满足拆成两部分,使得两部分单词都在树上.
    然后其实直接从树上找一个单词
    把是单词结尾的位置压栈
    然后暴力枚举断点检验即可.
    */
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #define MAXN 300001
    #define MAXM 50001
    using namespace std;
    int tot;
    char s[MAXM][27];
    struct data{int next[27];bool b;bool w;}
    tree[MAXN];
    void Add_tree(int l,char s[])
    {
        int now=0;
        for(int i=0;i<l;i++)
        {
            int x=s[i]-96; 
            if(tree[now].next[x]) now=tree[now].next[x];
            else tot++,tree[now].next[x]=tot,now=tot;
        }
        tree[now].b=true;
    }
    bool jd(int l,char s[])
    {
        int i=0,top=0,stack[1001],now=0;
        while(s[i])
        {
            if(tree[now].next[s[i]-96]) now=tree[now].next[s[i]-96];
            else return 0;
            if(tree[now].b&&s[i])//所谓割点
              stack[top++]=i+1;
            i++;
        }
        while(top)//检验 
        {
            int now=0;
            bool flag=1;
            int x=stack[--top];
            while(s[x])
            {
                if(!tree[now].next[s[x]-96]){flag=false;break;}
                now=tree[now].next[s[x]-96];
                x++;
            }
            if(tree[now].b&&flag)//该结点是单词的结尾
              return 1;
        }
        return 0;
    }
    int main()
    {
        int i=1;
        while(gets(s[i])&&strlen(s[i]))
        {
            int l=strlen(s[i]);
            Add_tree(l,s[i]);
            i++;
        }
        for(int j=1;j<=i;j++)
        {
            int l=strlen(s[j]);
            if(jd(l,s[j]))
              cout<<s[j]<<endl;
        }
        return 0;
    }
  • 相关阅读:
    MS SQL Server迁移至Azure SQL
    Aras Innovator 11 sp2 firefox客户端设置
    Aras Innovator 11 sp2 IE客户端设置
    Aras Innovator 11 sp2安装
    JDK Windows安装
    mocha测试es6问题
    jQuery中animate与scrollTop、offset().top实例
    AI下载步骤
    Visual Studio Code必备插件
    Visual Studio code快捷键
  • 原文地址:https://www.cnblogs.com/nancheng58/p/10068131.html
Copyright © 2011-2022 走看看