UVa: 10391 - Compound Words

題目描述:給出一個詞典,找出所有的複合詞,即恰好有兩個單詞連接而成的單詞。輸入每行都是一個由小寫字母組成的單詞。輸入已按照字典序從小到大排序,且不超過12000個單詞。輸出所有的複合詞按照字典序從小到大排列。

思路:用set存儲所有的單詞,對於每個單詞,遍歷所有可能子單詞組合,然後判斷在set中是否都已經存儲,若是則輸出該單詞。算法複雜度爲O(n*lgn*|S|),其中|S|表示單詞最大長度。

代碼如下:

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <sstream>
#include <fstream>

using namespace std;

#define FILE

int main()
{
	#ifdef FILE
		ifstream in("data.txt");
		ofstream out("output.txt");
		cin.rdbuf(in.rdbuf());
		cout.rdbuf(out.rdbuf());
	#endif
	set<string> res;
	string str;
	while(cin>>str)
	{
		res.insert(str);
	}
	for(set<string>::iterator it=res.begin();it!=res.end();it++)
	{
		string a = *it;
		int n = a.size();
		for(int i=0;i<a.size();i++)
		{
			string pre = a.substr(0,i+1);
			string next = a.substr(i+1,n-i);
			if(res.find(pre)!=res.end()&&res.find(next)!=res.end())
			{
				cout<<a<<endl;
				break;
			}
		}
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章