题目描述
Given N string S[1], S[2]......, S[N], you are to find a pair of strings whose longest common prefix has the largest length.
输入
There are multiple test cases. For each case:
The first line is a integer N. (2 <= N <= 20000)
The next N lines each contains a non-empty string S[i]. The length of S[i] is at most 50.
输出
For each case output a line representing the length of longest common prefix.
样例输入
3 bcabc bcd abcd
样例输出
2
我只想说这个题真的不难,可是它是我提交次数最多的几题了,我真的晕死了
这是一道Trie树的应用题,在每次插入的时候记录一下就可以了,可是我一开始用链表写,不知道内存超出了多少次,后来改用数组,还是超内存,不知道为什么,后
仔细的看了看这个题,发现不必弄那么多变量,于是就把所有变量去掉,就是
- structTrie
- {
- bool isStr;
- int step;
- intnext;
- }trie[maxn][26];
改成
- int trie[maxn][26];
这样这个题才过,而且运行错误无数次
#include<map> #include<set> #include<queue> #include<cmath> #include<vector> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define inf 0x0f0f0f0f using namespace std; const double pi=acos(-1.0); const double eps=1e-8; typedef pair<int,int>pii; const int maxn=1000000; int trie[maxn][26]; int main() { //freopen("in.txt","r",stdin); int cur,len; int alloc=1,n,m,sum; char s[51]; while(scanf("%d",&n)!=EOF) { memset(trie,-1,sizeof(trie)); sum=0; alloc=1; for (int i=0;i<n;i++) { scanf("%s",s); len=strlen(s); cur=0; for (int j=0;j<len;j++) { if (trie[cur][s[j]-'a']==-1) { trie[cur][s[j]-'a']=alloc; //trie[cur][s[j]-'a'].step=j+1; //sum=max(trie[cur][s[j]-'a'].step,sum); alloc++; } else sum=max(j+1,sum); //if (j==len-1) trie[cur][s[j]-'a'].isStr=true; cur=trie[cur][s[j]-'a']; } } printf("%d ",sum); } //fclose(stdin); return 0; }