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]<<"
    ";
    }
    
  • 相关阅读:
    图片处理中的Dithering技术
    网络I/O模型
    并发编程(二)
    并发编程(一)
    socket编程(二)
    socket编程(一)
    异常处理
    软件开发规范
    面向对象进阶
    多态与封装
  • 原文地址:https://www.cnblogs.com/kuronekonano/p/11135858.html
Copyright © 2011-2022 走看看