hdu5510 Bazinga 暴力+剪枝

本文介绍了一种算法,用于解决给定一系列字符串时如何找出最大的索引i,使得存在一个小于i的索引j,且Sj不是Si的子串。文章详细解释了输入输出格式,并提供了一个具体的实现案例。

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 (1in) such that there exists an integer j (1j<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 (1t50) which is the number of test cases.
For each test case, the first line is the positive integer n (1n500) 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;
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值