数据结构实验 7-17 字符串关键字的散列映射 (25分)

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1100;
int vis[maxn], sc[maxn];
int n, p;

struct Node{
    int hs;
    char s[10];
}t[maxn];

int Hash(char *s){
    int l = strlen(s), hs = 0, q = 1;
    if(l>3){
        for(int i = l-3; s[i]; i++){
            hs = hs*32+ (s[i]-'A');
        }
    }
    else{
        for(int i = 0; s[i]; i++){
            hs = hs*32 + (s[i]-'A');
        }
    }
    //cout << hs << endl;
    hs %= p;
    //cout << hs << endl;
    return hs;
}

int main(){
    char s[10];
    // sc[0] = 0;
    // for(int i  = 1; i <= 100; i++){
    //     if(i%2==0) sc[i] = -(i*i)/4;
    //     else sc[i] = (i+1)*(i+1)/4;
    // }

    scanf("%d%d",&n,&p); getchar();
    for(int i = 0; i < n; i++){
        scanf("%s",s);
        //cout << s << endl;
        int hs = Hash(s);
        //cout << hs << ' ' << endl;
        int tmp = hs,k=1;
        if(vis[hs]){
            if(strcmp(t[hs].s, s)!=0){
                while(vis[hs]){
                    hs = (tmp+k*k)%p;
                    if(!vis[hs]){
                        vis[hs] = 1;
                        break;
                    }
                    else if(strcmp(t[hs].s, s)==0){
                        break;
                    }
                    hs = (tmp-k*k+p)%p;
                    if(!vis[hs]){
                        vis[hs] = 1;
                        break;
                    }
                    else if(strcmp(t[hs].s, s)==0){
                        break;
                    }
                    k++;
                }
            }
        }
        else vis[hs] = 1;
        strcpy(t[hs].s, s);
        if(i==0) printf("%d",hs);
        else printf(" %d", hs);  
    }
    printf("\n");
    system("pause");
    return 0;
}
/*
4 11
A A A A
4 11
ZZZZZZZ AAAAAAA A Z
3 0 1 4
*/

仅供参考 切勿抄袭
hang hang hang !!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值