迷之好奇
阿新 • • 發佈:2018-12-18
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
這類題目使用動態分配的方式會超記憶體,所以要採用靜態分配空間的方法。
(字典樹)
#include <stdio.h>
#include <stdlib.h>
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
const int maxn = 2000050 ;
char str[10];
int tail = 1;
struct treenode {
int num;
treenode *next[10];
}treespace[maxn];
void reset();
void updata();
int Search();
int main() {
int n;
while(cin >> n) {
reset();
tail = 1;
for(int i = 0; i < n; i++) {
cin >> str;
updata();
}
int m;
cin >> m;
for(int i = 0; i < m; i++) {
cin >> str;
printf("%d\n", Search());
}
}
return 0;
}
int Search() {
int len = strlen(str);
treenode *now = &treespace[0];
for(int i = len-1; i >= 0; i--) {
if(now->next[str[i] - '0'] == NULL) {
return 0;
}
now = now->next[str[i] - '0'];
}
return now->num;
}
void updata() {
int len = strlen(str);
treenode *now = &treespace[0];
for(int i = len-1; i > 0; i--) {
if(now->next[str[i] - '0'] == NULL) {
now->next[str[i] - '0'] = &treespace[tail++];
}
now = now->next[str[i] - '0'];
now->num ++;
}
}
void reset() {
for(int i = 0; i < tail; i++) {
treespace[i].num = 0;
for(int j = 0; j < 10; j++) {
treespace[i].next[j] = NULL;
}
}
}