zoukankan      html  css  js  c++  java
  • HDU 1247

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247

    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

    题意:

    “帽子单词”是指,若字典中的某个词,它是由其他任意两个单词连接起来组成的,则称它为“帽子单词”。

    现在以字典序给出字典中的所有单词(不超过 $5e4$ 个),让你求出全部“帽子单词”。

    题解:

    先把字典建成字典树,然后对于每个单词,暴力地分成两个子串查找即可。

    AC代码:

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn=5e4+5;
    
    namespace Trie
    {
        const int SIZE=maxn*32;
        int sz;
        struct TrieNode{
            int ed;
            int nxt[26];
        }trie[SIZE];
        void init(){sz=1;}
        void insert(const string& s)
        {
            int p=1;
            for(int i=0;i<s.size();i++)
            {
                int ch=s[i]-'a';
                if(!trie[p].nxt[ch]) trie[p].nxt[ch]=++sz;
                p=trie[p].nxt[ch];
            }
            trie[p].ed++;
        }
        int search(const string& s)
        {
            int p=1;
            for(int i=0;i<s.size();i++)
            {
                p=trie[p].nxt[s[i]-'a'];
                if(!p) return 0;
            }
            return trie[p].ed;
        }
    };
    int tot;
    string s[maxn];
    int main()
    {
        ios::sync_with_stdio(0);
        cin.tie(0), cout.tie(0);
        Trie::init();
        tot=0;
        while(cin>>s[++tot]) Trie::insert(s[tot]);
        for(int i=1;i<=tot;i++)
        {
            bool ok=0;
            for(int k=1;k<s[i].size();k++)
            {
                if(Trie::search(s[i].substr(0,k)) && Trie::search(s[i].substr(k,s[i].size()-k)))
                {
                    ok=1;
                    break;
                }
            }
            if(ok) cout<<s[i]<<'
    ';
        }
    }
  • 相关阅读:
    C++ for(char c:s)遍历字符串||for (char c : s)和for (char& c : s)的区别
    二维数组的查找--剑指offer(C++)
    C++学习笔记之--boolalpha
    在C++中matrix.size()和matrix [0] .size()之间的区别是什么?
    C3_note
    用webpack4从零开始构建react脚手架
    php
    正则表达式基础
    DOM
    常用H5
  • 原文地址:https://www.cnblogs.com/dilthey/p/9974165.html
Copyright © 2011-2022 走看看