hash hdu1247 Hat’s Words

题意:有多少个字符串,能恰好被另外两个字符串拼接而成

一般查询某个字符串是否存在,,其实都能用hash水过去

思路:枚举字符串,再枚举哪两个字符串组成它,看这两个字符串是否存在

#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<iostream>
#include<functional>
#include<algorithm>

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 1e5 + 5;
const int HS = 1000007;

char word[MX][100];
int H_head[HS], H_next[MX], H_rear;

int Hash(char*S) {
    int len = strlen(S), ret = 0;
    for(int i = 0; i < len; i++) {
        ret = ret * 131 + S[i];
    }
    return (ret & 0x7fffffff) % HS;
}

void Hash_init() {
    H_rear = 0;
    memset(H_head, -1, sizeof(H_head));
    memset(H_next, -1, sizeof(H_next));
}

bool Hash_query(char*S) {
    int h = Hash(S);

    for(int i = H_head[h]; ~i; i = H_next[i]) {
        if(strcmp(word[i], S) == 0) return true;
    }
    return false;
}

void Hash_add(int id) {
    int h = Hash(word[id]);

    for(int i = H_head[h]; ~i; i = H_next[i]) {
        if(strcmp(word[i], word[id]) == 0) return;
    }

    H_next[id] = H_head[h];
    H_head[h] = id;
}

int main() {
    //freopen("input.txt", "r", stdin);
    int tot = 0;
    Hash_init();
    while(~scanf("%s", word[tot])) {
        Hash_add(tot++);
    }

    char temp[100];
    for(int i = 0; i < tot; i++) {
        int L = strlen(word[i]);
        for(int j = 1; j < L; j++) {
            memcpy(temp, word[i], sizeof(char) * j);
            temp[j] = 0;
            if(Hash_query(temp) && Hash_query(word[i] + j)) {
                printf("%s\n", word[i]);
                break;
            }
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值