UVA 10391 Compound Words

本文介绍了一种高效算法,用于在字典中查找所有能由两个其他单词组成的复合词。通过使用哈希表(map),该算法能在接近O(n)的时间复杂度内完成任务。

 

Problem E: Compound Words

 

You are to find all the two-word compound words in a dictionary. A two-word compound word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.

Input

Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 120,000 words.

Output

Your output should contain all the compound words, one per line, in alphabetical order.

Sample Input

a
alien
born
less
lien
never
nevertheless
new
newborn
the
zebra

 

Sample Output

alien
newborn

题意:输入一些单词。要输出其中,可以由两个单词拼接组合成的单词。。

思路:题中数据有12W,,直接暴力时间复杂度为肯定会超时。。需要高效的方法

我是用map,输入的时候把每个单词标记成1。然后每个单词找过去。每个单词从每个字母位置分成2个单词。如果2个单词均是有标记成1的,代表这个单词可以被组合,就输出来

这样做的话。时间复杂度接近于O(n)。。。A之。。

 

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <map>
using namespace std;

char ci[122222][25];
int len;
map<string, int> adj;
int main()
{
    int n = 0;
    while (gets(ci[n]) != NULL)
    {
	adj[ci[n]] = 1;
	n ++;
    }	
    for (int i = 0; i < n ; i ++)
    {
	len = strlen(ci[i]);
	for (int j = 1; j < len - 1; j ++)
	{
	    char a[25], b[25];
	    for (int k = 0; k < j; k ++)
		a[k] = ci[i][k];
	    a[j] = '\0';
	    for (int k = j; k < len; k ++)
		b[k - j] = ci[i][k];
	    b[len - j] = '\0';
	    if (adj[a] == 1 && adj[b] == 1)
	    {
		printf("%s\n", ci[i]);
		break;
	    }
	}
    }
    return 0;
}


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值