UVa 10391 - Compound Words

7 篇文章 0 订阅

好久没有1Y了 ~~~

hash来做,先将所有字符串存入哈希表,然后将每一个字符串分成两个子串,分成的两个子串能在哈希表中找到,则其为“compound words”,将其输出。

代码如下:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;

const int MAXSIZE = 120002;
int num, head[MAXSIZE], next[MAXSIZE];
char a[120002][50];
int Hash(char *str) // BKDR字符串哈希函数
{
    int seed = 131, sum = 0;
    while(*str)
        sum = sum * seed + (*str++);
    return (sum & 0x7FFFFFFF) % MAXSIZE;
}
void insert(int s) // 将所有单词插入哈希表
{
    int h = Hash(a[s]);
    next[s] = head[h];
    head[h] = s;
}
int find(char *s) // 查找单词
{
    int h = Hash(s);
    int u = head[h];
    while(u)
    {
        if(!strcmp(a[u], s))
            return 1;
        u = next[u];
    }
    return 0;
}
int main()
{
#ifdef test
    freopen("sample.txt", "r", stdin);
#endif
    int num = 1, len;
    char str1[50], str2[50];
    while(scanf("%s", a[num++]) != EOF)
        insert(num-1);
    for(int i=1; i<=num; i++)
    {
        len = strlen(a[i]);
        for(int j=1; j<len; j++)
        {
            for(int k=0; k<j; k++)
                str1[k] = a[i][k];
            str1[j] = 0;
            strcpy(str2, &a[i][j]);
            if(find(str1) && find(str2))
            {
                printf("%s\n", a[i]);
                break;
            }
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值