Repository
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Problem Description
When you go shopping, you can search in repository for avalible merchandises by the computers and internet. First you give the search system a name about something, then the system responds with the results. Now you are given a lot merchandise names in repository and some queries, and required to simulate the process.
Input
There is only one case. First there is an integer P (1<=P<=10000)representing the number of the merchanidse names in the repository. The next P lines each contain a string (it's length isn't beyond 20,and all the letters are lowercase).Then there is an integer Q(1<=Q<=100000) representing the number of the queries. The next Q lines each contains a string(the same limitation as foregoing descriptions) as the searching condition.
Output
For each query, you just output the number of the merchandises, whose names contain the search string as their substrings.
Sample Input
20 ad ae af ag ah ai aj ak al ads add ade adf adg adh adi adj adk adl aes 5 b a d ad s
Sample Output
0 20 11 11 2
Source
题意:给你n个单词,接下来有m个询问,每个询问一个单词,问每个单词是这n个单词中多少个的子串
思路:假设我们对n个单词中的每一个都建立从i到j建立字典树,最坏情况是总共有2000000个结点,在承受范围内
接下来我们又会发现如果我们对每个单词的每个子串都插入字典树,会有重复的情况,比如abba,会查找a时abba这个单词的贡献就为2
所以需要一个特定的序列号来区分是否是同一序列中的子串。
我们可以定义一个belong,若belong相同,则跳过,若不同,则+1后更新belong。
#include <cstring>
#include <vector>
#include <cstdio>
#include<stack>
using namespace std;
const int maxnode = 20000 * 100 + 10;
const int sigma_size = 26;
char s[110],s1[110];
// 字母表为全体小写字母的Trie
struct Trie {
int ch[maxnode][sigma_size];
int val[maxnode];
int belong[maxnode];
int sz; // 结点总数
void clear() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); } // 初始时只有一个根结点
int idx(char c) { return c - 'a'; } // 字符c的编号
void insert(int l,int r,int num) {
int u = 0;
for(int i = l; i < r; i++) {
int c = idx(s[i]);
if(!ch[u][c]) { // 结点不存在
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz]=1;
belong[sz]=num;
ch[u][c] = sz++; // 新建结点
}
u = ch[u][c]; // 往下走
if(num!=belong[u]){
val[u]+=1;
belong[u]=num;
}
}
}
int find(const char* s){
int u=0,len=strlen(s);
for(int i=0;i<len;i++){
int c=idx(s[i]);
if(!ch[u][c])
return 0;
u=ch[u][c];
}
return val[u];
}
};
Trie trie;
int main()
{
int n,m;
while(scanf("%d",&n)!=EOF){
trie.clear();
for(int i=1;i<=n;i++){
scanf("%s",s);
int len=strlen(s);
for(int j=0;j<len;j++)
trie.insert(j,len,i);
}
scanf("%d",&m);
while(m--){
scanf("%s",s);
printf("%d\n",trie.find(s));
}
}
return 0;
}