zoukankan      html  css  js  c++  java
  • HDU

    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<stdio.h>///字典树
    #include<string.h>
    #include<string>
    #include<vector>
    #include<algorithm>
    #include<iostream>
    #define pb push_back
    using namespace std;
    int tot;
    int tre[50005][26];
    bool vis[50005];
    vector<string>v,ans;
    int insert(string str,int rt)///插入单词
    {
        for(int j=0; j<str.size(); j++)///遍历单词string
        {
            int x=str[j]-'a';
            if(tre[rt][x]==0)///新节点
                tre[rt][x]=++tot;///节点编号
            rt=tre[rt][x];///下一个节点
        }
        vis[rt]=true;///单词末尾标记
    }
    bool finds(string str,int rt)///查询
    {
        for(int i=0; i<str.size(); i++)
        {
            int x=str[i]-'a';
            if(tre[rt][x]==0)return false;
            rt=tre[rt][x];
        }
        return vis[rt];
    }
    int main()
    {
        tot=0;
        int num=++tot;
        memset(vis,false,sizeof(vis));
        memset(tre[num],0,sizeof(tre[num]));
        string a;
        v.clear();
        ans.clear();
        while(cin>>a)///建树
            insert(a,num),v.pb(a);
        for(int i=0; i<v.size(); i++)
        {
            for(int j=0; j<v[i].size(); j++)
            {
                string tma=v[i].substr(0,j+1);
                string tmb=v[i].substr(j+1);
    //            cout<<tma<<"======"<<tmb<<endl;
                if(finds(tma,num)&&finds(tmb,num))
                {
                    ///一旦当前单词确定是ans,则可以不用再遍历这个单词剩余的组合
                    ans.pb(v[i]);
                    break;
                }
            }
        }
        sort(ans.begin(),ans.end());
        for(int i=0; i<ans.size(); i++) cout<<ans[i]<<"
    ";
    }
    
  • 相关阅读:
    Spark源码走读4——Scheduler
    Spark源码走读3——Job Runtime
    Spark源码走读2——Spark Submit
    Spark源码走读1——RDD
    Tachyon源码解读一:master部分
    VS2008中MFC界面编程Caption中文全是乱码的解决办法
    程序猿也爱学英语(上),有图有真相
    C++程序员必看书单
    如何将CString转换成WCHAR
    Windows 语音识别编程
  • 原文地址:https://www.cnblogs.com/kuronekonano/p/11135858.html
Copyright © 2011-2022 走看看