Test instructions gives you a set of phone numbers to determine if one of the phones is a prefix for another phone
The basic application of the dictionary tree can first put all the phones into the trie to mark the end character of each phone and then query each number to see if there is an end tag, which means that the number is the prefix of this number
Actually the insertion is done to know if a number is prefixed with another number, assuming a is a prefix of B.
If a is inserted before B, then insert B will encounter the end tag of a.
Weak A is inserted after B and then a node after the insert is complete and a non-empty child node.
This will only be used at each insert to determine the line can be omitted to eliminate the query this step
Pointers and dynamic memory allocation implementation dictionaries are easier, but not releasing memory when there are multiple sets of samples can cause the MLE to free up memory and spend more unnecessarily time on the tle, so it's better to use arrays.
#include <cstdio> #include <cstring>using namespace std;const int N = 10005;char tel[n][12];int trie[n * 10][10 ], L;bool end[n *, Flag;void Inittrie () //Empty trie{ L = 1; memset (trie, 0, sizeof (trie)); memset (end, 0, sizeof (end));} void Inserttrie (char s[]) //Insert { int r = 0, i = 0, J; while (S[i]) { if (end[r]) flag = false; End tag with other numbers j = s[i++]-' 0 '; if (!trie[r][j]) trie[r][j] = l++; r = trie[r][j]; } for (int i = 0; i < ++i) //Insert completed node and child node if (trie[r][i]) flag = false; End[r] = true;} int main () { int T, n; scanf ("%d", &t); while (t--) { inittrie (); scanf ("%d", &n); Flag = true; for (int i = 0; i < n; ++i) { scanf ("%s", Tel[i]); Inserttrie (Tel[i]); } Puts (flag?) "YES": "NO"); } return 0;} Last modified: 2015-07-27 19:36
Phone List
Problem Descriptiongiven A list of phone numbers, determine if it is consistent in the sense this no number is the prefix of another. Let ' s say the phone catalogue listed these numbers:
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it's not possible-to-call Bob, because-the central would direct your-to-the-emergency line as soon as Y OU had dialled the first three digits of Bob ' s phone number. So the list would not being consistent.
Inputthe first line of input gives a single integer, 1 <= t <=, the number of test cases. Each test case is starts with N, the number of the phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with a unique phone number on each line. A phone number is a sequence of at the most ten digits.
Outputfor each test case with output "YES" If the list is consistent, or "NO" otherwise.
Sample Input
2391197625999911254265113123401234401234598346
Sample Output
NOYES
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU Phone List (trie array Implementation)