HihoCoder #1014 : Trie树

1.题面

http://hihocoder.com/problemset/problem/1014

2.题意

一开始输入n,随后有n个字符串,记为集合A,然后输m,有m个询问,每个询问为一个字符串b,问A中有多少个以b为前缀的字符串。

3.思路

就是单纯的tire练习题

4.代码

/*****************************************************************
    > File Name: cpp_acm.cpp
    > Author: Uncle_Sugar
    > Mail: uncle_sugar@qq.com
    > Created Time: Sun 02 Oct 2016 12:42:56 CST
*****************************************************************/
# include <cstdio>
# include <cstring>
# include <cctype>
# include <cmath>
# include <cstdlib>
# include <climits>
# include <iostream>
# include <iomanip>
# include <set>
# include <map>
# include <vector>
# include <stack>
# include <queue>
# include <algorithm>
using namespace std;

# define rep(i,a,b) for (i=a;i<=b;i++)
# define rrep(i,a,b) for (i=b;i>=a;i--)

struct QuickIO{
	QuickIO(){const int SZ = 1<<20;
		setvbuf(stdin ,new char[SZ],_IOFBF,SZ);
		setvbuf(stdout,new char[SZ],_IOFBF,SZ);
	}				//*From programcaicai*//
}QIO;

template<class T>void PrintArray(T* first,T* last,char delim=' '){
    for (;first!=last;first++) cout << *first << (first+1==last?'\n':delim);
}

/*
1.see the size of the input data before you select your algorithm 
2.cin&cout is not recommended in ACM/ICPC
3.pay attention to the size you defined, for instance the size of edge is double the size of vertex
*/

const int debug = 1;
const int size  = 100 + 1000000; 
const int INF = INT_MAX>>1;
typedef long long ll;

struct node{
	int nxt[26], cnt, end;
};

struct Tire{
	node T[size];
	int tot, root;
	void init(){tot = 1;root = newnode();};
	int newnode(){
		//# cout << "tot = " << tot << endl;
		memset(T[tot].nxt, 0, sizeof(T[tot].nxt));
		T[tot].cnt = T[tot].end = 0;
		return tot++;
	}
	inline int index(char ch){return ch - 'a';}
	void insert(char *str){
		int tp = root;
		while ((*str) != '\0'){
			//# cout << "*str = " << char(*str) << endl;
			//# cout << "tp = " << tp << endl;
			if (T[tp].nxt[index(*str)] == 0) T[tp].nxt[index(*str)] = newnode();
			tp = T[tp].nxt[index(*str)];
			T[tp].cnt++;
			++str;
		}
		T[tp].end++;
	}
	int ask(char *str){
		int tp = root;
		while ((*str) != '\0'){
			tp = T[tp].nxt[index(*str)];
			if (tp == 0) return 0;
			++str;
		}
		return T[tp].cnt;
	}
}tire;

char str[size];
int main()
{
	/*std::ios::sync_with_stdio(false);cin.tie(0);*/
	int n, m;
	while (~scanf("%d", &n)){
		tire.init();
		while (n--){
			scanf("%s", str);
			//# cout << str << endl;
			tire.insert(str);
		}
		scanf("%d", &m);
		while (m--){
			scanf("%s", str);
			int ans = tire.ask(str);
			printf("%d\n", ans);
		}
	}
	return 0;
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/sinat_29278271/article/details/52723493
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞