NOJ1601 several statistics hash simple application
Description
In a scientific research survey, n natural numbers are obtained, each of which cannot exceed 1500000000 (1.5*109 ). It is known that the number of different numbers cannot exceed 10000. Now we need to count the number of occurrences of these natural numbers and output the statistical results in the order of ascending natural numbers.
Question Input
Multiple groups of input data
Each group of data contains n + 1 rows:
The row 1st is an integer n, indicating the number of natural numbers.
2nd ~ N + 1 rows have a natural number per line.
Question output
Data Output in each group contains m rows (m is the number of different numbers in n natural numbers) and is output in ascending order of natural numbers. Each row outputs two integers, which are natural numbers and the number of occurrences of these integers, separated by a space.
Sample Input
8
2
4
2
4
5
100
2
100
Sample output
2 3
4 2
5 1
100 2
Solutions
The idea of not using HASH is to define a struct with two parameters: the value of this number and the number of occurrences of this number. Then we open an array of 10000 struct. Each time we read a number, we will first check whether we have read it before. If we have read it, we will add it to the end if we haven't read it.
This algorithm is correct, but it obviously does not work for 200000 of Data O (n ^ 2). Therefore, HASH is used to optimize the use of arrays. The idea is that every time you read a number, it will modulo a prime number similar to 10000, and then use the calculated value as the subscript (assuming it is t ). If there is no number, you can simply put it in. If we find that s [t]. num is exactly the number of reads, then s [t]. cnt ++. If this location is found to be occupied but s [t]. num is not, locate the first unoccupied location and save it here. In this way, the HASH function is used to optimize the array.
Finally, sort out all the valid values in the array, and output the sort.
For details, see the code.
#include
#include
#include using namespace std;const int maxn = 10020;struct node { int num; int cnt;};node s[maxn];node temp[maxn];bool cmp(node a,node b) { return a.num < b.num;}int main(){ int n; while(scanf("%d",&n) != EOF) { for(int i = 1 ; i < maxn ; i ++) { s[i].num = -1; s[i].cnt = 1; } while(n--) { int a; scanf("%d",&a); int t = a%10009; while(1) { if(s[t].num == a) { s[t].cnt ++; break; } if(s[t].num == -1) { s[t].num = a; break; } t ++; } } int pt = 1; for(int i = 1 ; i < maxn ; i ++) { if(s[i].num != -1) { temp[pt].num = s[i].num; temp[pt++].cnt = s[i].cnt; } } sort(temp+1,temp+pt,cmp); for(int i = 1 ; i < pt ; i ++) { printf("%d %d\n",temp[i].num,temp[i].cnt); } } return 0;}