题目链接:acm.hdu.edu.cn/showproblem.php?pid=1277
题目大意:给出一个信息流文件由数字组成,然后再给出若干关键字,检索那些关键字出现过。
分析:用字典树,将关键字序列构造为字典树,然后用信息流文件当做模式串,迭代模式串的每一位,
并在字典树中查找是否存在子串,存在就输出.
(注意:要检查关键字是否重复输出)
代码如下:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <ctype.h>
#include <cmath>
#include <stack>
#include <queue>
#include <sstream>
#include <set>
#include <map>
#include <vector>
#include <limits.h>
using namespace std;
typedef long long ll;
const int N = 600000 + 10;
int tree[N][10];
int num[N];
string arr[60100];
string big = "";
int pos = 1, n, m, co = 1;
set<int > s;
vector<int> ss;
void insert(string a){
int root = 0;
for(int i = 0; i < a.length(); i++){
int n = a[i] - '0';
if(!tree[root][n]){
tree[root][n] = pos++;
}
root = tree[root][n];
}
num[root] = co++;
}
void find(string a){
int root = 0;
for(int i = 0; i < a.length(); i++){
int n = a[i] - '0';
if(!tree[root][n]){
return ;
}
root = tree[root][n];
if(num[root]){
if(!s.count(num[root])){
ss.push_back(num[root]);
s.insert(num[root]);
}
return ;
}
}
}
void finds(string a){
for(int i = 0; i < a.length(); i++){
string b = a.substr(i,a.length());
find(b);
}
}
int main(){
cin >> n >> m;
for(int i = 0; i < n; i++){
cin >> arr[i];
big += arr[i];
}
for(int i = 0; i < m; i++){
string a, b;
cin >> b >> b >> b >> a;
insert(a);
}
finds(big);
if(!ss.empty()){
cout << "Found key:";
for(vector<int>::iterator it = ss.begin(); it != ss.end(); it++){
printf(" [Key No. %d]", *it);
}
cout << endl;
}else{
cout << "No key can be found !" << endl;
}
return 0;
}