hdu5510 Bazinga 暴力+剪枝

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;
}




發佈了198 篇原創文章 · 獲贊 8 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章