zoukankan      html  css  js  c++  java
  • pat 1078

    1078 Hashing (25分)
     

    The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be ( where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.

    Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.

    Input Specification:
    Each input file contains one test case. For each case, the first line contains two positive numbers: MSize (≤) and N (≤) which are the user-defined table size and the number of input numbers, respectively. Then N distinct positive integers are given in the next line. All the numbers in a line are separated by a space.

    Output Specification:
    For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print "-" instead.

    Sample Input:
    4 4
    10 6 4 15

    Sample Output:
    0 1 4 -



    题意:模拟散列表存储,发生冲突时采用正向平方探测,散列表的大小要求为比给定值大或相等的素数

    思路:首先用打表的方法求出素数,根据给定的表的大小m找到最小的比m大的素数。根据输入的数值往散列表里面插入

    坑点:1.平方探测法是循环的,当探测范围大于表的size之后,需要对size取余
       2.测试点1给定的表长是0或1,注意打表的时候把0和1也规为非素数


     1 #include<cstdio>
     2 bool prime[100010]={false};
     3 bool isTrue[100010]={false};
     4 int m,n;
     5 void getPrime(){
     6     for(int i=2;i<100010;i++){
     7         if(prime[i]==false){
     8             for(int j=i*2;j<100010;j+=i){
     9                 prime[j]=true;
    10             }
    11         }
    12     }
    13 }
    14 void insert(int key){
    15     for(int step=0;step<m;step++){
    16         int index=(key+step*step)%m;
    17         if(isTrue[index]==false){
    18             isTrue[index]=true;
    19             printf("%d",index%m);
    20             return;
    21         }
    22     }
    23     printf("-");
    24 }
    25 int main(){
    26     getPrime();
    27     prime[1]=prime[0]=true;
    28     int key;
    29     scanf("%d%d",&m,&n);
    30     while(prime[m]!=false){
    31         m++;
    32     }
    33     for(int i=0;i<n;i++){
    34         scanf("%d",&key);
    35         if(i!=0)
    36             printf(" ");
    37         insert(key);
    38     }
    39     return 0;
    40 } 
  • 相关阅读:
    session的生命周期
    临远的spring security教程
    spring security原理图及其解释
    解决eclipse中出现Resource is out of sync with the file system问题
    从SOA到BFV【普元的一份广告文章】
    普元OA平台介绍
    门户平台
    企业门户平台解决方案
    使用 CAS 在 Tomcat 中实现单点登录
    CAS 跨域原理
  • 原文地址:https://www.cnblogs.com/foodie-nils/p/13151555.html
Copyright © 2011-2022 走看看