HDU-5510 Bazinga

来源:互联网 发布:java电子商务网站源码 编辑:程序博客网 时间:2024/06/05 12:47
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 (1in) i (1≤i≤n) such that there exists an integer j (1j<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".
Input
The first line contains an integer t (1t50) t (1≤t≤50) which is the number of test cases.
For each test case, the first line is the positive integer n (1n500) 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.
Output
For each test case, output the largest label you get. If it does not exist, output1 −1.
Sample Input
45ababczabcabcdzabcd4youlovinyouaboutlovinyouallaboutlovinyou5dedefabcdabcdeabcdef3abaccc
Sample Output
Case #1: 4Case #2: -1Case #3: 4
并查集加KMP
#include<cstdio>#include<algorithm>#include<cstring>#define maxn 2000#define maxm 550using 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
0 0
原创粉丝点击