您的位置:首页 > 其它

HDU4287 字典树

2015-07-26 20:04 267 查看
字典树建树,然后dfs搜索即可

//#pragma comment(linker, "/STACK:1677721600")
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define inf (-((LL)1<<40))
#define lson k<<1, L, (L + R)>>1
#define rson k<<1|1,  ((L + R)>>1) + 1, R
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define mem(a, b) memset(a, b, sizeof(a))
#define FIN freopen("in.txt", "r", stdin)
#define FOUT freopen("out.txt", "w", stdout)
#define rep(i, a, b) for(int i = a; i <= b; i ++)
#define dec(i, a, b) for(int i = a; i >= b; i --)

template<class T> T MAX(T a, T b) { return a > b ? a : b; }
template<class T> T MIN(T a, T b) { return a < b ? a : b; }
template<class T> T GCD(T a, T b) { return b ? GCD(b, a%b) : a; }
template<class T> T LCM(T a, T b) { return a / GCD(a,b) * b;    }

//typedef __int64 LL;
typedef long long LL;
const int MAXN = 100000 + 100;
const int MAXM = 110000;
const double eps = 1e-8;
LL MOD = 1000000007;

int t, n, m;
char str[10], s1[5005][10];
int tree[30010][27], s, ans;
bool val[30010];//val[i] = 1表示是某个字符串的尾节点
vector<int>e[12];

void init() {
int cnt = 5;
rep (i, 'a', 'z') {
cnt += 1 + (i == 's' || i == 'z' ? -1 : 0);
e[cnt / 3].push_back(i - 'a');
}
}

void insert_to_tree(char* str)
{
int u = 0;
for(int i = 0; str[i]; i ++)
{
int c = str[i] - 'a';
if(!tree[u][c])
{
tree[u][c] = ++s;
val[s] = 0;
}
u = tree[u][c];
}
val[u] = 1;
}

void dfs(int u, int k, char *s, int n) {
ans += val[u] && k == n;
int p = s[k] - '0', sz = e[p].size();
rep (i, 0, sz - 1) {
int v = e[p][i];
if(tree[u][v] && k < n)
dfs(tree[u][v], k + 1, s, n);
}
}

int main()
{
//    FIN;
init();
cin >> t;
while(t--) {
s = 0;
mem0(tree); mem0(val);
scanf("%d %d%*c", &n, &m);
rep (i, 0, n - 1) scanf("%s", s1[i]);
rep (i, 1, m) {
scanf("%s", str);
insert_to_tree(str);
}
rep (i, 0, n - 1) {
ans = 0;
dfs(0, 0, s1[i], strlen(s1[i]));
cout << ans << endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: