HDU-5510 Bazinga

4 篇文章 0 订阅
3 篇文章 0 订阅
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, output 1  −1.
Sample Input
4
5
ab
abc
zabc
abcd
zabcd
4
you
lovinyou
aboutlovinyou
allaboutlovinyou
5
de
def
abcd
abcde
abcdef
3
a
ba
ccc
Sample Output
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值