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 Act 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
Train of Thought: This question is whether to use the hash function to match the string or not, but it seems wise to be a stack application in terms of processing, because I didn't quite understand this question at the beginning, so I paid 100 points to download others.
It takes a long time to understand the code. In the sorting of Two-Dimensional String arrays, the sort function is further deepened and cannot be directly sorted. The two-dimensional arrays cannot be directly sorted in sort. Stack raises the time
It is much higher than linear conditions.
#include <cstdio>#include <cstring>#include <algorithm>#include<iostream>using namespace std;struct node{ int len; char a[55];}e[100005];int Stack[100005];bool operator < (node b,node c){ for(int i=0;i<c.len&&i<b.len;i++) { if(b.a[i]<c.a[i]) return true; else if(b.a[i]>c.a[i]) return false; } return b.len<c.len;}int hash(char *s,int len){ int sum=0; for(int i=0;i<len;i++) sum=sum*26+s[i]-'a'; return sum;}int main(){ int n,i,sum=0,top=0; cin>>n; for(i=1; i<=n; i++) { scanf("%s",e[i].a); e[i].len=strlen(e[i].a); } sort(e+1,e+n+1); for(i=1;i<=n;i++) { while((top)&&e[i].len<=e[Stack[top]].len||hash(e[Stack[top]].a,e[Stack[top]].len)!=hash(e[i].a,e[Stack[top]].len)) top--; Stack[++top]=i; if(sum<top) sum=top; //cout<<sum<<' '<<top<<' '<<i<<endl; } cout<<sum<<endl; return 0;}