【1078】Hashing (25 分)

简介: 【1078】Hashing (25 分)【1078】Hashing (25 分)
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>  
#include<map>
#include<vector>
#include<queue> 
using namespace std;  
key:散列函数H(key)=key%TSize,解决冲突使用二次方探查法
可证明得:如果步长step从0~TSize-1枚举仍然无法找到位置,则step≥TSize也不可能找到位置了
const int N=11111;
bool isPrime(int n){  //判断n是否素数
  if(n <= 1)  return false;
  int sqr=(int)sqrt(1.0*n);
  for(int i=2;i<=sqr;i++){ 
    if(n%i == 0)  return false;
  }
  return true;
}
bool hashTable[N]={0};//hashTable[x] == false 则x号位未被使用
int main(){   
  int n,TSize,a;
  scanf("%d%d",&TSize,&n);
  while(isPrime(TSize) == false){  //寻找第一个≥TSize的质数
    TSize++;
  }
  for(int i=0;i<n;i++){ 
    scanf("%d",&a);
    int M=a%TSize; 
    if(hashTable[M] == false) {  //如果M号位未被使用,则已找到
      hashTable[M]=true;
      if(i == 0)  printf("%d",M);
      else printf(" %d",M);
    }else {
      int step; //二次方探查法步长
      for(step=1;step < TSize ;step++){  //可以证明TSize为循环节
        M=(a+step*step)%TSize;  //下一次检测值
        if(hashTable[M] == false){  //如果M号位置未被使用,则已找到
          hashTable[M]=true;
          if(i == 0)  printf(" %d",M);
          else printf(" %d",M);
          break;//记住要break
        }
      }
      if(step >=TSize){  //找不到插入的地方
        if(i >0) printf(" ");
        printf("-");
      }
    }
  }        
  system("pause"); 
    return 0;   
}
相关文章
|
5月前
|
算法 测试技术 C++
【动态规划】【C++算法】2518. 好分区的数目
【动态规划】【C++算法】2518. 好分区的数目
|
5月前
|
存储 缓存 负载均衡
一致性 Hash 算法 Hash 环发生偏移怎么解决
一致性 Hash 算法 Hash 环发生偏移怎么解决
134 1
问题 A: DS哈希查找—线性探测再散列
问题 A: DS哈希查找—线性探测再散列
101 0
|
2月前
|
存储 缓存 负载均衡
Rendezvous hashing算法介绍
Rendezvous hashing算法介绍
52 3
Rendezvous hashing算法介绍
|
5月前
|
算法 数据可视化 数据处理
Algorithms_算法专项_Hash算法的原理&哈希冲突的解决办法
Algorithms_算法专项_Hash算法的原理&哈希冲突的解决办法
46 0
|
存储 缓存 算法
【第五天】算法图解--哈希表(散列表)Hash函数
【第五天】算法图解--哈希表(散列表)Hash函数
|
存储 缓存 负载均衡
【算法技术专题】如何用Java实现一致性 hash 算法( consistent hashing )(上)
【算法技术专题】如何用Java实现一致性 hash 算法( consistent hashing )(上)
316 0
【算法技术专题】如何用Java实现一致性 hash 算法( consistent hashing )(上)
|
存储 搜索推荐 算法
物以类聚,数以"桶"分
"桶"在数据结构与算法领域可以说是有着重要的应用,从简单的排序算法到某些特定数据结构,运用桶的思想考虑问题往往有出人意料的效果。
165 0
物以类聚,数以"桶"分
【1145】Hashing - Average Search Time (25分)【hash 平方探测法】
【1145】Hashing - Average Search Time (25分)【hash 平方探测法】 【1145】Hashing - Average Search Time (25分)【hash 平方探测法】
109 0
【1122】Hamiltonian Cycle (25分)【图论】
【1122】Hamiltonian Cycle (25分)【图论】 【1122】Hamiltonian Cycle (25分)【图论】
108 0