HDU-1277全文检索 (字典树)

21 篇文章 0 订阅
1 篇文章 0 订阅

题目链接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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值