迷之好奇
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
Source
zmx
裸字典树(倒着创建树)
#include <bits/stdc++.h>
using namespace std;
struct node
{
int cnt; //出现该数字的次数
int nextt[11]; // 存下一层的代号 就是那个top的值
};
node tree[1000000];
int top;
int creat()
{
memset(tree[top].nextt, -1, sizeof(tree[top].nextt));
tree[top].cnt = 0;
return top++; // 返回代号
}
void insert(int k, char *str)
{
int len = strlen(str);
for (int i = len - 1; i >= 0; i--)
{
int index = str[i] - '0';
if (tree[k].nextt[index] == -1)
tree[k].nextt[index] = creat();
tree[k].cnt++; //出现该数字的次数
k = tree[k].nextt[index]; // 将下一层的对应的代数(top)赋给k
}
}
int search(int k, char *str)
{
int len = strlen(str);
for (int i = len - 1; i >= 0; i--)
{
int index = str[i] - '0';
if (tree[k].nextt[index] == -1)
return 0; // 只要一个找不到就返回 0
k = tree[k].nextt[index]; // 找到 将该数的下一层的代数传给K
}
return tree[k].cnt; // 数字出现次数
}
int main()
{
int m, n;
char s[19];
while (cin >> n)
{
top = 0;
int root = creat();
for (int i = 0; i < n; i++)
{
cin >> s;
insert(root, s);
}
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> s;
int ans = search(root, s);
cout << ans << endl;
}
// cout<<endl;
}
return 0;
}