Ladies and gentlemen, please sit up straight.
Don't tilt your head. I'm serious.
For n n given strings S 1 ,S 2 ,⋯,S n S1,S2,⋯,Sn, labelled from 1 1 to n n, you should find the largest i (1≤i≤n) i (1≤i≤n) such that there exists an integer j (1≤j<i) j (1≤j<i) and S j Sj is not a substring of S i Si.
A substring of a string S i Si is another string that occurs in S i Si. For example, ``ruiz" is a substring of ``ruizhang", and ``rzhang" is not a substring of ``ruizhang".
Don't tilt your head. I'm serious.
For n n given strings S 1 ,S 2 ,⋯,S n S1,S2,⋯,Sn, labelled from 1 1 to n n, you should find the largest i (1≤i≤n) i (1≤i≤n) such that there exists an integer j (1≤j<i) j (1≤j<i) and S j Sj is not a substring of S i Si.
A substring of a string S i Si is another string that occurs in S i Si. For example, ``ruiz" is a substring of ``ruizhang", and ``rzhang" is not a substring of ``ruizhang".
For each test case, the first line is the positive integer n (1≤n≤500) n (1≤n≤500) and in the following n n lines list are the strings S 1 ,S 2 ,⋯,S n S1,S2,⋯,Sn.
All strings are given in lower-case letters and strings are no longer than 2000 2000 letters.
4 5 ab abc zabc abcd zabcd 4 you lovinyou aboutlovinyou allaboutlovinyou 5 de def abcd abcde abcdef 3 a ba ccc
Case #1: 4 Case #2: -1 Case #3: 4
并查集加KMP
#include<cstdio> #include<algorithm> #include<cstring> #define maxn 2000 #define maxm 550 using namespace std; int n; int fa[maxm], R[maxm]; char ne[maxn]; struct node { char st[maxn]; int pos; }s[maxm]; void init() { for (int i = 1; i <= n; i++) { fa[i] = i; R[i] = 1; } } int find(int x) { if (x == fa[x]) return x; else return fa[x] = find(fa[x]); } void unit(int a, int b) { a = find(a); b = find(b); if (a == b) return; else { fa[b] = a; R[a] += R[b]; } } bool KMP(char a[], char b[]) { int la = strlen(a); int lb = strlen(b); for (int i = 0, j = -1; i <= lb; i++, j++) { ne[i] = j; while (j != -1 && b[i] != b[j]) j = ne[j]; } for (int i = 0, j = 0; i <= la; i++, j++) { if (j == lb) return true; while (j != -1 && a[i] != b[j]) j = ne[j]; } return false; } int main() { int T; scanf("%d", &T); for (int h = 1; h <= T; h++) { scanf("%d", &n); init(); for (int i = 1; i <= n; i++) { scanf("%s", s[i].st); s[i].pos = i; } int l=-1; for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { if (find(s[j].pos) == j) { if (KMP(s[i].st, s[j].st)) { unit(s[i].pos, s[j].pos); } else { int la = i; l = max(l, la); } } } } if (l == -1) printf("Case #%d: -1\n", h); else printf("Case #%d: %d\n", h, l); } }
Case #4: 3