Ultimate Array
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic Discuss
Problem Description
bLue 这次又获得了一个更厉害的数组,欣喜之余,他想知道某个数字在数组中出现了多少次,你能帮助他吗?
Input
输入数据有多组(数据组数不超过 20),到 EOF 结束。
对于每组数据:
第 1 行输入 2 个用空格隔开的整数 n, q (1 <= n, q <= 10^5),分别表示数组中数字的个数和询问的次数。
第 2 行输入 n 个用空格隔开的整数 ai (0 <= ai <= 10^9),表示数组中的数字。
接下来 q 行,每行输入一个整数 v (0 <= v <= 10^9),表示要询问的数字。
Output
对于每组数据:
每次询问输出一行,包含一个整数,表示 bLue 询问的数字在数组中出现的次数。
每组数据末尾输出一行空行。
Example Input
6 4
2 0 2 666 666 2
0
2
666
7
Example Output
1
3
2
0
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}ST;
int a[100000], n;
ST *h[100000];//哈希表链式存储
void creat(int x)
{
ST *p;
int i;
i = x % n;//对它取余,将x存到 i下标的 链表里面
p = (ST *)malloc(sizeof(ST));
p->data = x;
p->next = h[i];//插入到头
h[i] = p;
}
int find(int x)
{
ST *p;
int i, num = 0;
i = x % n;
for(p = h[i]; p; p = p->next)//暴力查找
{
if(p->data == x)//找到相同的于x 统计出现的次数
num++;
}
return num;//返回出现的次数
}
int main()
{
int i, m, num;
while(~scanf("%d %d", &n, &m))
{
for(i = 0; i < n; i++)
{
h[i] = NULL;//初始化每个下标的头,虽然这样有点浪费内存,但是这个题目不超内存。如果对时间要求不高的话,可以暴力free掉
}
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
creat(a[i]);//储存进hash
}
while(m--)
{
scanf("%d", &num);
printf("%d\n", find(num));//输出出现的次数
}
printf("\n");
}
return 0;
}