Description
Description
N words are given and sorted by length. If a word I is the prefix of a word J, I-> J is counted as a solitaire (two identical words cannot be counted as a solitaire ).
Your task is to find the longest dragon for the input words.
Input description
Input description
First behavior n (1 <= n <= 105 ). Each of the following n rows contains one word (in lowercase), which is sorted by length. (Length of each word <50)
Output description
Output description
The maximum length of a dragon.
Sample Input
Sample Input
5
I
A
Int
Able
Inter
Sample output
Sample output
3
Data range and prompt
Data size & hint
1 <= n <= 105
First, sort the strings in Lexicographic Order, then strings with the same prefix will get together, and then store the length of the dragon with a String Stack.
/* Author: nowandforever question: p1051 solitaire game */# include <cstdio> # include <stack> # include <string> # include <vector> # include <algorithm> using namespace STD; bool Pd (string, string B) // judge whether string B is a substring of string a {int L =. size (), I; int P = B. size (); If (L <= P) return 0; // if the length of a is less than or equal to that of B (the same word cannot be used) for (I = 0; I <p; I ++) // determines that if there are differences in the range of B, it will jump out of {if (a [I]! = B [I]) return 0;} return 1;} int main () // This inspires us to sort all words in Lexicographic Order, in this way, words with the same prefix are "squeezed" together {int N, I; char s [55]; scanf ("% d", & N ); vector <string> input; // easy to save strings and sort for (I = 0; I <n; I ++) {scanf ("% s", S); input. push_back (s);} Sort (input. begin (), input. end (); // The default value is from small to large stack <string> map; // defines a String Stack int ret = 0; for (I = 0; I <N; I ++) {// then we maintain a stack and enumerate all strings (sorted in Lexicographic Order). If the current string can be connected to the string at the top of the stack, while (! Map. Empty ()&&(! Pd (input [I], map. top () // then the current string is added to the stack and continues to enumerate the Next string. If the next string cannot be received, the top string of the stack is displayed, // The current string continues to be compared with the top stack string after the pop-up, until the current string and the top stack string can be connected to Jackie Chan, then the current string into the stack, map. pop (); map. push (input [I]); If (map. size ()> RET) // count the maximum number of elements in the stack during this period. ret = map. size ();} printf ("% d \ n", RET); Return 0 ;}
CODEVS-1051 Solitaire games