迷之好奇
Time Limit: 2000 ms Memory Limit: 65536 KiB
Problem Description
FF得到了一个有n个数字的集合。不要问我为什么,有钱,任性。
FF很好奇的想知道,对于数字x,集合中有多少个数字可以在x前面添加任意数字得到。
如,x = 123,则在x前面添加数字可以得到4123,5123等。
Input
多组输入。
对于每组数据
首先输入n(1<= n <= 100000)。
接下来n行。每行一个数字y(1 <= y <= 100000)代表集合中的元素。
接下来一行输入m(1 <= m <= 100000),代表有m次询问。
接下来的m行。
每行一个正整数x(1 <= x <= 100000)。
Output
对于每组数据,输出一个数字代表答案。
Sample Input
3 12345 66666 12356 3 45 12345 356
Sample Output
1 0 1
Hint
建立字典树,一共分为四个函数,分别是建立字典树的根节点的函数,插入函数,查找函数,主函数。
此题还需要注意的一点是要把输进去的数字都拆开一个数字一个数字的插入,查找的时候如果遇到没有这个就会返回0,反之返回这个节点的记录下的数据。
Accepted:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int data; //记录这个字符串出现了几次
struct node *next[26];//26个字母一共有26个孩子
};
struct node a[1001000]; //设置一个静态数组
int top;
struct node *creat() //首先建立一个空树
{
struct node *root = &a[top++];
int i;
root->data = 0; //首先置为0
for(i = 0;i < 26;i++)
{
root->next[i] = NULL; //26个孩子全部置为空
}
return root;
}
struct node *insert(struct node *root,int s) //插入以后的数字
{
struct node *p = root; //在设置一个指向树根的节点
int i, t;
for(i = 0;s > 0;i++)
{
t = s%10; //分离各位数字,与水仙花数相同
s = s/10;
if(p->next[t] == NULL) //如果当前的数字失控的话就会重新走一遍建树的函数
p->next[t] = creat();
p = p->next[t]; //反之就会去找下一个
p->data++; //记录该节点出现的次数
}
p->data--; //之所以要减去一个一是本身不用记录
return root;
}
int find(struct node *root,int s)
{
struct node *p = root;
int i, t;
for(i = 0;s > 0;i++)
{
t = s%10;
s = s/10;
if(p->next[t] == NULL)
return 0; //如果没有查找到就会返回0;
p = p->next[t];//继续寻找下一个数
}
return p->data; //如果找到就会返回当前的节点
}
int main()
{
int n,m, x,y;
while(~scanf("%d",&n))
{
top = 0;
struct node *root = creat(); //先建树
while(n--)
{
scanf("%d",&x);
root = insert(root,x); //插入当前的数
}
scanf("%d",&m);
while(m--)
{
scanf("%d",&y);
printf("%d\n",find(root,y)); //查找是否有改数字
}
}
return 0;
}