Hash(c++)

这是一个C++程序,用于计算字符串的哈希值并进行排序。程序读取多个字符串,利用131作为基数计算每个字符串的哈希值,然后对哈希值进行排序。最后输出不重复字符串的数量。
摘要由CSDN通过智能技术生成

#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
using namespace std;
char a[10005];
int n,m,k;
long long base; 
long long ans;
long long num[10005];
int main(){
  freopen("3370.in","r",stdin);
   freopen("3370.out","w",stdout);
    scanf("%d",&n);
    k=n;ans=0;base=131;
    for(int i=1;i<=n;i++){
        scanf("%s",&a);
        m=strlen(a);
        for(int j=0;j<m;j++){
            num[i]=(num[i]*base+a[j])%212370440130137957;
        }
    }
   /

下面是一个简单的线性探测法哈希表的实现(C语言): ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define TABLE_SIZE 1000 struct hash_node { char *key; char *value; }; struct hash_table { struct hash_node *table[TABLE_SIZE]; }; unsigned int hash_function(const char *key) { unsigned int hash = 0; int i; for (i = 0; i < strlen(key); i++) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash % TABLE_SIZE; } struct hash_table *hash_create() { struct hash_table *hash = malloc(sizeof(struct hash_table)); int i; for (i = 0; i < TABLE_SIZE; i++) { hash->table[i] = NULL; } return hash; } void hash_destroy(struct hash_table *hash) { int i; for (i = 0; i < TABLE_SIZE; i++) { struct hash_node *node = hash->table[i]; if (node != NULL) { free(node->key); free(node->value); free(node); } } free(hash); } void hash_set(struct hash_table *hash, const char *key, const char *value) { unsigned int slot = hash_function(key); struct hash_node *node = hash->table[slot]; int i = 0; while (node != NULL) { if (strcmp(node->key, key) == 0) { free(node->value); node->value = strdup(value); return; } i++; slot = (slot + i) % TABLE_SIZE; node = hash->table[slot]; } node = malloc(sizeof(struct hash_node)); node->key = strdup(key); node->value = strdup(value); hash->table[slot] = node; } char *hash_get(struct hash_table *hash, const char *key) { unsigned int slot = hash_function(key); struct hash_node *node = hash->table[slot]; int i = 0; while (node != NULL) { if (strcmp(node->key, key) == 0) { return node->value; } i++; slot = (slot + i) % TABLE_SIZE; node = hash->table[slot]; } return NULL; } int main() { struct hash_table *hash = hash_create(); hash_set(hash, "name", "John"); hash_set(hash, "age", "30"); printf("Name: %s, Age: %s\n", hash_get(hash, "name"), hash_get(hash, "age")); hash_destroy(hash); return 0; } ``` 这个哈希表使用了一个简单的哈希函数,可以根据需要进行修改。在这个哈希表中,冲突的时候使用了线性探测法来解决。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值