当前位置: 代码迷 >> 综合 >> Trie树 hdu4287 Intelligent IME
  详细解决方案

Trie树 hdu4287 Intelligent IME

热度:53   发布时间:2023-12-14 04:02:24.0

题意:告诉你手机按键对应了哪些字母,然后再告诉你一些单词

问按对应的数字对应了多少个给出的单词


思路:将单词构造成字典树,然后用对应的数字在字典树上查询

#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<iostream>
#include<functional>
#include<algorithm>using namespace std;
typedef long long LL;
typedef pair<LL, int> PLI;const int MX = 1e3 + 5;
const int INF = 0x3f3f3f3f;char S[10];
vector<string>G;
char table[][10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};struct Node {int num;Node *Next[26];Node() {num = 0;memset(Next, NULL, sizeof(Next));}
};void trie_add(Node*root, char*S) {int L = strlen(S);Node *p = root;for(int i = 0; i < L; i++) {int id = S[i] - 'a';if(p->Next[id] == NULL) {p->Next[id] = new Node();}p = p->Next[id];}p->num++;
}int trie_query(Node*root, int pos, int L) {int ans = 0;int id = S[pos] - '0';for(int i = 0; i < strlen(table[id]); i++) {int w = table[id][i] - 'a';if(root->Next[w] != NULL) {if(pos + 1 == L) {ans += root->Next[w]->num;} else {ans += trie_query(root->Next[w], pos + 1, L);}}}return ans;
}int main() {//freopen("input.txt", "r", stdin);int T, n, m;scanf("%d", &T);while(T--) {G.clear();Node *root = new Node();scanf("%d%d", &n, &m);for(int i = 1; i <= n; i++) {scanf("%s", S);G.push_back(string(S));}for(int i = 1; i <= m; i++) {scanf("%s", S);trie_add(root, S);}for(int i = 0; i < n; i++) {strcpy(S, G[i].c_str());printf("%d\n", trie_query(root, 0, strlen(S)));}}return 0;
}