hash表

https://oj.neu.edu.cn/problem/60

 

学习哈希姿势

#include<cstdio>
#include<cstring>
using namespace std;

const int maxn = 120007, HASH = 119993;
int head[HASH], nxt[maxn], INDEX;
char str[maxn][20];
int getkey(char* s){
    int sum = 0;
    for(int i = 0; s[i]; i++){
        sum = (sum*13+s[i])%HASH;
    }
    return sum%HASH;
}
void insert(int pos){
    int h = getkey(str[pos]);
    int u = head[h];
    while(u){
        if(strcmp(str[u], str[pos]) == 0){
            //puts("chongfule");
            return;
        }
        u = nxt[u];
    }
    nxt[pos] = head[h];
    head[h] = pos;
}
bool inside(char* s){
    int h = getkey(s);
    int u = head[h];
    while(u){
        if(strcmp(str[u], s) == 0){
            return true;
        }
        u = nxt[u];
    }
    return false;
}
bool compound(int i){
    int len = (int)strlen(str[i]);
    char a[20], b[20];
    for(int j = 1; j < len; j++){
        strcpy(a, str[i]);
        a[j] = '\0';
        strcpy(b, str[i]+j);
        if(inside(a) && inside(b))
            return true;
    }
    return false;
}

int main(){
    INDEX = 0;
    while(scanf("%s", str[++INDEX])!=EOF){
        insert(INDEX);
    }
    for(int i = 1; i <= INDEX; i++){
        if(compound(i))
            printf("%s\n", str[i]);
    }
    return 0;
}

 

posted @ 2017-10-16 21:44  DearDongchen  阅读(154)  评论(0编辑  收藏  举报