HDU 1251 统计难题(字典树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?

pid=1251


题意:先给出字典。每次查询一个单词,求以该单词为前缀的个数。


思路:裸字典树


代码

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <string>

using namespace std;

#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define ceil(x, y) (((x) + (y) - 1) / (y))

const int SIZE = 30;
const int N = 1e6 + 10;
const int INF = 0x7f7f7f7f;

struct Trie {
	int val[SIZE];
	int count;//以从根结点到当前结点的字符串为前缀的单词个数
};

int sz;
Trie ch[N];

int newnode() {
	memset(ch[sz].val, 0, sizeof(ch[sz].val));
	ch[sz].count = 0;
	return sz++;
}

void insert(char *s) {
	int u = 0;
	for (int i = 0; s[i] != ''; i++) {
		int idx = s[i] - 'a';
		if (!ch[u].val[idx]) {
			ch[u].val[idx] = newnode();
		}
		u = ch[u].val[idx];
		ch[u].count++;
	}
}

int findpre(char *s) {
	int u = 0;
	for (int i = 0; s[i] != ''; i++) {
		int idx = s[i] - 'a';
		if (!ch[u].val[idx])
			return 0;
		u = ch[u].val[idx];
	}
	return ch[u].count;
}

int main() {
	char str[SIZE];
	sz = 0;
	newnode();
	while (gets(str) && str[0]) {
		insert(str);
	}
	while (scanf("%s", str) != EOF) {
		printf("%d
", findpre(str));
	}
	return 0;
}


原文地址:https://www.cnblogs.com/wzzkaifa/p/7169272.html