【1145】Hashing - Average Search Time (25分)【hash 平方探测法】

简介: 【1145】Hashing - Average Search Time (25分)【hash 平方探测法】【1145】Hashing - Average Search Time (25分)【hash 平方探测法】
#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;  
//插入时pos = (a + j * j) % tsize,j是从0~tsize-1的数字
//查询时pos = (a + j * j) % tsize,其中j <= tsize
bool isprime(int n){//判断是否是素数
  for(int i=2;i*i<=n;i++){
    if(n%i==0)  return false;
  }
  return true;
}
int main(){   
    int tsize,n,m,a;//表长,要插入个数,查询个数
    scanf("%d %d %d",&tsize,&n,&m);
    while(!isprime(tsize))  tsize++;//大于表长的最大素数
    vector<int>v(tsize);
    for(int i=0;i<n;i++){
      scanf("%d",&a);
      int flag=0;
      for(int j=0;j<tsize;j++){
        int pos=(a+j*j)%tsize;
        if(v[pos]==0){
          v[pos]=a;
          flag=1;
          break;
        }
      }
      if(!flag) printf("%d cannot be inserted.\n",a);
    }
    int ans=0;
    for(int i=0;i<m;i++){
      scanf("%d",&a);
      for(int j=0;j<=tsize;j++){
        ans++;
        int pos=(a+j*j)%tsize;
        if(v[pos]==a||v[pos]==0) break;
        //找到或者没找到(不存在)都退出
      }
    }
    printf("%.1lf\n",ans*1.0/m);
    system("pause");
    return 0;
}
相关文章
|
7月前
|
存储 数据安全/隐私保护
均匀散列函数(Uniform Hash Function)
均匀散列函数(Uniform Hash Function)是一种将不同长度的输入数据映射到相同大小的输出数据的散列函数。均匀散列函数的主要特点是,对于相同的输入数据,无论其长度如何,都会得到相同的输出散列值。这种散列函数常用于数据结构的存储和查找,例如哈希表、散列表等。
111 3
|
11月前
|
C++
【PAT甲级 - C++题解】1145 Hashing - Average Search Time
【PAT甲级 - C++题解】1145 Hashing - Average Search Time
58 0
LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero
LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
PAT (Advanced Level) Practice - 1145 Hashing - Average Search Time(25 分)
PAT (Advanced Level) Practice - 1145 Hashing - Average Search Time(25 分)
100 0
【1078】Hashing (25 分)
【1078】Hashing (25 分) 【1078】Hashing (25 分)
70 0
【1134】Vertex Cover (25分)【hash散列】
【1134】Vertex Cover (25分)【hash散列】 【1134】Vertex Cover (25分)【hash散列】
84 0
【1063】Set Similarity (25 分)
【1063】Set Similarity (25 分) 【1063】Set Similarity (25 分)
76 0
【1046】Shortest Distance (20 分)
【1046】Shortest Distance (20 分) 【1046】Shortest Distance (20 分)
75 0