fork download
  1. #include <iostream>
  2. #include <cstring>
  3. #include <string>
  4. #define M 10 // M là số nút có trên bảng băm, đủ để chứa các nút nhập vào bảng băm
  5. #define NULLKEY -1
  6. using namespace std;
  7. struct Hash
  8. {
  9. int Bucket[M];
  10. };
  11. void initHash(Hash &H)
  12. {
  13. for(int i=0;i<M;i++)
  14. {
  15. H.Bucket[i]=NULLKEY;
  16. };
  17. };
  18. int Hashing(int k, int j)
  19. {
  20. if(j==0)return k%M;
  21. return (k%M+j*j)%M;
  22. };
  23. void insertHash(Hash &H,int k)
  24. {
  25. int j=0;
  26. int i=k%M;
  27. if(H.Bucket[i]==NULLKEY)
  28. {H.Bucket[i]=k;}
  29. else
  30. {
  31. for( j=0;j<M;j++){
  32. i=(k%M+j*j)%M;
  33. if (H.Bucket[i] == -1) {
  34. H.Bucket[i] = k;
  35. break;
  36. }
  37. if(j>=10){cout<<"\nBang bam bi day, khong them duoc";return;};
  38. };
  39.  
  40. };
  41.  
  42.  
  43. };
  44. void traverseAllHash(Hash H)
  45. {
  46. for(int i=0;i<M;i++)
  47. {
  48. if(H.Bucket[i]!=NULLKEY)
  49. cout<<i<<" --> "<<H.Bucket[i]<<endl;
  50. else
  51. cout<<i<<endl;
  52. };
  53. };
  54.  
  55. int main()
  56. {
  57. Hash H;
  58. initHash(H);
  59.  
  60. int n,x;cin>>n; // n la so luong gia tri can phai luu tru
  61. for (int i = 1; i<=n;i++)
  62. {
  63. cin>>x;
  64. cout<<"\nInsert "<<x;
  65. insertHash(H,x); // them 1 gia tri du lieu vao bang bam
  66. }
  67. cout<<"\nCreated Hash:"<<endl;
  68. traverseAllHash(H);
  69.  
  70. return 0;
  71. }
  72.  
  73.  
Success #stdin #stdout 0.01s 5344KB
stdin
12
6
63
6
73
36
41
87
21
38
6
77
71
stdout
Insert 6
Insert 63
Insert 6
Insert 73
Insert 36
Insert 41
Insert 87
Insert 21
Insert 38
Insert 6
Insert 77
Insert 71
Created Hash:
0 --> 36
1 --> 41
2 --> 21
3 --> 63
4 --> 73
5 --> 6
6 --> 6
7 --> 6
8 --> 87
9 --> 38