UVA10391- Compound Words

题意:找出一连串的字符串中,是否存在两个字符串相组合的字符串出现在所给的字符串中,如果有的话,将组合的那个字符串输出

思路:利用哈希函数,将每个单词分为两个部分,都存在哈希表中,搜索是否两个部分都存在,如果有的话,输出

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 120003
using namespace std;
typedef char Word[50];

const int HashSize = 120100;
Word word[MAXN];
int N, head[HashSize], next[HashSize];

void init_lookup_table() {
    memset(head, 0, sizeof(head));
}

int hash(char *str) {
    int hash = 0;
    while (*str) 
        hash = hash * 10 + (*str++);
    return (hash & 0x7FFFFFFF) % HashSize;
}

int add_hash(int s) {
    int h = hash(word[s]);
    int u = head[h];
    next[s] = head[h];
    head[h] = s;
    return 1;
}

int search(char *s) {
    int h = hash(s);
    int u = head[h];
    while (u) {
        if (strcmp(word[u], s) == 0) 
            return u; 
        u = next[u];
    }
    return 0;
}

int main() {
    Word str;
    N = 1;
    init_lookup_table();
    while (gets(word[N])) {
        if (word[N][0] == '\0')
            break;
        add_hash(N);
        N++; 
    }
    for (int i = 1; i < N; i++)
        if (word[i][1]) {
            for (int j = 0; j < strlen(word[i]) - 1; j++) {
                strcpy(str, word[i]); 
                str[j + 1] = '\0';
                if (search(str) && search(word[i] + j + 1)) {
                    puts(word[i]); 
                    break;
                }
            }    
        }
    return 0;
}


你可能感兴趣的:(UVA10391- Compound Words)