PAT甲级1078
来源:互联网 发布:win10图片查看软件 编辑:程序博客网 时间:2024/06/14 05:48
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 "H(key) = key % TSize" 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 (<=104) and N (<=MSize) 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 410 6 4 15Sample Output:
0 1 4 -
#include<cstdio>#include<vector>#include<algorithm>using namespace std;bool isPrime(int a){if (a < 2)return false;for (int i = 2; i <= sqrt(a); i++){if (a%i == 0)return false;}return true;}int smallestPrimeSize(int a){while(!isPrime(a)){a++;}return a;}int main(){int MSize, N;scanf("%d %d", &MSize, &N);int size = smallestPrimeSize(MSize);vector<bool> hashtable;for (int i = 0; i < size; i++){hashtable.push_back(true);}int t;for (int i = 0; i < N; i++){scanf("%d", &t);int temp = t%size;if (hashtable[temp]){hashtable[temp] = false;printf("%d", temp);if (i != N - 1)printf(" ");}else{int j = (temp+1)%size, k = 1;//这里必须模size,假如说temp=size-1,不模的话,最后一个测试点过不去bool flag = false;while (j < size){if (hashtable[j]){hashtable[j] = false;printf("%d", j);if (i != N - 1)printf(" ");break;}else{k++;//直到平方探测长度到size-1还不能找到位置,之后就不必在探测了if (k == size){flag = true;break;}}j =(temp + k*k)%size;}if (flag){printf("-");if (i != N - 1)printf(" ");}}}return 0;}
- PAT(甲级)1078
- PAT 甲级 1078 Hashing
- **浙大PAT甲级 1078
- PAT甲级1078
- PAT 甲级
- PAT甲级 A1025.PAT RANKING
- PAT 甲级 1025 PAT Ranking
- PAT(甲级)1003
- PAT(甲级)1004
- PAT(甲级)1005
- PAT(甲级)1006
- PAT(甲级)1007
- PAT(甲级)1008
- PAT(甲级)1009
- PAT(甲级)1010
- PAT(甲级)1011
- PAT(甲级)1012
- PAT(甲级)1013
- 文档总结
- bzoj1150 [CTSC2007]数据备份Backup
- 大家都在用的dialog MaterialDialog
- Solr Fields字段Copying Fields/Dynamic Fields
- intellij配置EJB项目入门
- PAT甲级1078
- 一步步移植uCOS-II and LwIP (四)
- 安装包方法
- 242. Valid Anagram
- 2017年1月21日
- 设计模式之适配器模式
- A+B Problem (sdut oj)
- ESP-TOUCH编码规则及解码
- 浣花溪公园(SPFA模板)