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
Hint
Author
「2017年寒假集训 结训赛2」bLue
一道典型的字典树问题,要注意的是,记得释放内存,不然会超内存……
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 12
#define MAXN 12
struct node
{
int data;
struct node * next[MAX];
};
struct node *creat()
{
struct node * p = (struct node *)malloc(sizeof(struct node));//不需要手动
p->data = 0;
for(int i=0;i<MAX;i++)
p->next[i] = NULL;
return p;
};
struct node * Initial()
{
return creat();
};//初始化
void Insert(struct node * root, char * s)
{
struct node * p = root;
for(int i=0;s[i];i++)
{
int t = s[i]-'0';
if(p->next[t]==NULL)
p->next[t] = creat();
p = p->next[t];
}
p->data++;
}
int Find(struct node * root, char * s)
{
struct node *p = root;
for(int i=0;s[i];i++)
{
int t = s[i] - '0';
if(p->next[t]==NULL)
return 0;
p = p->next[t];
}
return p->data;
}
void Fre(struct node * root)//释放内存
{
if(root)
{
for(int i=0;i<MAX;i++)
Fre(root->next[i]);
}
free(root);
}
int main()
{
int n, q;
while(~scanf("%d %d", &n, &q))
{
struct node * root;
root = Initial();
while(n--)
{
char a[12];
scanf("%s", a);
Insert(root, a);
}
while(q--)
{
char a[12];
scanf("%s", a);
printf("%d\n", Find(root, a));
}
Fre(root);
printf("\n");
}
return 0;
}