Question link: http://acm.nyist.net/JudgeOnline/problem.php? PID = 1, 290
Hash can also be used because the test data is large. However, note that the effects of CIN and cout on time are relatively large. Therefore, replace it with scanf and printf.
First, we will introduce the dictionary tree (tire) method.
The dictionary tree adopts a space-for-time strategy.
# Include <iostream>
# Include <string>
# Include <cstring>
Using namespace STD;
Struct Node
{
Int sum; // number of occurrences
Node * Next [26];
};
Int search (char * s, node * t)
{
Node * P, * q;
P = T;
Int I = 0, ID, J;
While (s [I])
{
Id = s [I]-'A ';
If (p-> next [ID] = NULL) // if the branch is empty, set the node
{
Q = new node;
Q-> sum = 0;
For (j = 0; j <26; ++ J)
Q-> next [J] = NULL;
P-> next [ID] = Q;
}
P = p-> next [ID]; // continue searching along the branch
++ I;
}
(P-> sum) ++;
Return p-> sum; // The number of times the string appears at the end.
}
Int main ()
{
Int N, I, max = 0;
Node * t = new node;
For (I = 0; I <26; ++ I) {T-> next [I] = NULL; t-> sum = 0 ;}
Char temp [50], name [50];
Cin> N;
For (I = 0; I <n; ++ I)
{
Cin> temp;
Int num = search (temp, t );
If (Num> MAX)
{
Max = num;
Strcpy (name, temp );
}
}
Cout <name <"" <max <Endl;
System ("pause ");
Return 0;
}