您的位置:首页 > 其它

hdu5510 Bazinga 暴力+剪枝

2016-11-05 10:04 429 查看


Bazinga

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 3567    Accepted Submission(s): 1146


Problem Description

Ladies and gentlemen, please sit up straight.
Don't tilt your head. I'm serious.



For n given
strings S1,S2,⋯,Sn,
labelled from 1 to n,
you should find the largest i (1≤i≤n) such
that there exists an integer j (1≤j<i) and Sj is
not a substring of Si.

A substring of a string Si is
another string that occurs in 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 (1≤t≤50) which
is the number of test cases.

For each test case, the first line is the positive integer n (1≤n≤500) and
in the following n lines
list are the strings S1,S2,⋯,Sn.

All strings are given in lower-case letters and strings are no longer than 2000 letters.

 

Output

For each test case, output the largest label you get. If it does not exist, output −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
Case #4: 3

 

i从0到n - 1遍历,用一个vis标记j是否是其后面某个i的子串,是的话vis[j] = 1,否则vis[j] = 0,在遍历i = i + 1的时候

如果遍历前面的vis[j] == 1的话,就不算这个j,原因是,从i - 1到j + 1这一段,假如遇到了一个x不是i的子串,那么直接记录了flag = i,继续更新前面vis[x] == 0的看是不是i的子串,是的话修改vis[x] = 1;如果是i的子串的话,那么前面打上vis[x] == 1的肯定是后面的子串,因为我们是从后往前扫的,在扫到后面的时候,如果后面的是i的子串了的话,那么前面的还是这个子串的子串,肯定是i的子串,没有必要匹配了,达到剪枝的目的

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

int T, n, kase;
char a[505][2005];
int vis[505];

int main()
{
cin >> T;
kase = 0;
while (T--) {
scanf("%d", &n);
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; i++) {
scanf("%s", a[i]);
}
int flag = 0;
for (int i = 0; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (!vis[j]) {
if (strstr(a[i], a[j]) == NULL) flag = i + 1;
else vis[j] = 1;
}
}
}
if (flag == 0) flag = -1;
printf("Case #%d: %d\n", ++kase, flag);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu