UVa 10391 Compound Words(字符串+查找)

来源:互联网 发布:java 多线程http代理 编辑:程序博客网 时间:2024/05/21 06:26

原题地址

https://vjudge.net/problem/UVA-10391

按照字典序输入一个词典,输出其中所有的复合词。复合词是指可以由字典中任意两个不同的单词组合而成的词,比如new+born=newborn

解题思路

本题是《算法竞赛入门经典》的习题5-5,一道水题,但是需要一点小技巧。

最直接想到的是一个O(n^2)的遍历,看每对字符串拼接后的词是否在原来的词典里,但是由于n有120000那么大,所以超时了- -

换一种思路,如果拆一下每个词看看拆分后的两部分是否都在词典里,那么复杂度就在O(n*m)的级别了,一般的单词长度都不会很长(100以内),所以复杂度还是降下来足以AC了。

AC代码

#include <iostream>#include <set>#include <string>using namespace std;int main(){    set<string> dict, res;    string str, tmp, s1, s2;    while(cin >> str)        dict.insert(str);    for (auto it = dict.begin(); it != dict.end(); ++it) //遍历字典里每个词    {        str = *it;        for (int len = 1; len < str.length(); ++len) //拆分str        {            s1 = str.substr(0, len);            s2 = str.substr(len);            if (dict.count(s1) && dict.count(s2)) //拆分后都能找到                res.insert(str);        }    }    for (auto it = res.begin(); it != res.end(); ++it)        cout << *it << endl;    return 0;}
0 0