File size: 2,308 Bytes
c4b0eef |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
/*
****************************************************************
****************************************************************
-> Coded by Stavros Chryselis
-> Visit my github for more solved problems over multiple sites
-> https://github.com/StavrosChryselis
-> Feel free to email me at [email protected]
****************************************************************
****************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <ctype.h>
#define gc() getchar()
using namespace std;
struct ver
{
int words;
int prefixes;
struct ver **edges;
};
void initialize(ver **vertex)
{
int i;
(*vertex) = (struct ver*)malloc(sizeof(struct ver));
(*vertex)->words = 0;
(*vertex)->prefixes = 0;
(*vertex)->edges = (struct ver**)malloc(sizeof(ver) * 26);
for (i = 0; i<26; i++)
(*vertex)->edges[i] = NULL;
}
void addword(ver **vertex, string &word, int pos = 0)
{
if (pos == word.size())
{
(*vertex)->words++;
(*vertex)->prefixes++;
return;
}
char k = word[pos];
(*vertex)->prefixes++;
if ((*vertex)->edges[k - 'a'] == NULL)
initialize(&(*vertex)->edges[k - 'a']);
addword(&(*vertex)->edges[k - 'a'], word, pos + 1);
}
int countwords(ver *vertex, string &word, int pos = 0)
{
if (pos == word.size())
return vertex->words;
char k = word[pos];
if (vertex->edges[k - 'a'] == NULL)
return 0;
return countwords(vertex->edges[k - 'a'], word, pos + 1);
}
int countprefixes(ver *vertex, string &word, int pos = 0)
{
if (pos == word.size())
return vertex->prefixes;
char k = word[pos];
if (vertex->edges[k - 'a'] == NULL)
return 0;
return countprefixes(vertex->edges[k - 'a'], word, pos + 1);
}
inline void next_string(string &A)
{
A.clear();
char c = gc();
while (isspace(c))
c = gc();
while (!isspace(c) && c != EOF)
{
A.push_back(c);
c = gc();
}
}
struct ver *trie;
int N, Q;
inline void init()
{
string S;
scanf("%d %d", &N, &Q);
initialize(&trie);
while (N--)
{
next_string(S);
addword(&trie, S);
}
}
inline int query()
{
string S;
next_string(S);
return countprefixes(trie, S);
}
int main()
{
// freopen("input.txt", "r", stdin);
init();
while (Q--)
printf("%d\n", query());
return 0;
}
|