1. 程式人生 > >HDU1238——Substrings【KMP,列舉】

HDU1238——Substrings【KMP,列舉】

Substrings

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12486    Accepted Submission(s): 6001


 

Problem Description

You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.

 

 

Input

The first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string. 

 

 

Output

There should be one line per test case containing the length of the largest string found.

 

 

Sample Input

 

2 3 ABCD BCDFF BRCD 2 rose orchid

 

 

Sample Output

 

2 2

 

 

Author

Asia 2002, Tehran (Iran), Preliminary

 

 

Recommend

Eddy   |   We have carefully selected several similar problems for you:  1010 1239 1240 1016 1242 

題目大意:給你一組字串,問這組字串的最長公共子串是多長,並且如果這個子串的反轉是字串的子串則也可認為是他的子串。

大致思路:我們可以列舉第一個字串的所有子串,然後用KMP演算法看在其他字串中能否找到他或者他的反轉。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAXN = 100010;
string s[MAXN];
int NextVal[MAXN];

void GetNextVal(string a){
	NextVal[0] = -1;
	for(int i = 1,j = -1; i < a.size(); i++){
		while(j > -1 && a[i] != a[j + 1]) j = NextVal[j];
		if(a[i] == a[j + 1]) j++;
		NextVal[i] = j;
	}
}

bool KMP(string a,string b){
	for(int i = 0, j = -1; i < b.size(); i++){
		while(j > -1 && (j == a.size() - 1 || b[i] != a[j + 1])) j = NextVal[j];
		if(b[i] == a[j + 1]) j++;
		if(j == a.size() - 1){
			return true;
		}
	}
	return false;
}

int main(int argc, char const *argv[])
{
	int t;
	scanf("%d",&t);
	while(t--){
		int n;
		scanf("%d",&n);
		for(int i = 0; i < n; i++)
			cin >> s[i];
		string ans = "";
		for(int i = 0; i < s[0].size();i++){
			for(int j = 1; j <= s[0].size() - i; j++){
				string op1 = s[0].substr(i,j);
				string op2 = op1;
				reverse(op2.begin(),op2.end());
				bool flag1 = true,flag2 = true;
				GetNextVal(op1);
				for(int k = 1; k < n; k++){
					if(!KMP(op1,s[k])){ flag1 = false; break; }
				}
				GetNextVal(op2);
				for(int k = 1; k < n; k++){
					if(!KMP(op2,s[k])){ flag2 = false; break;}
				}
				if(flag1 || flag2){
					if(ans.size() <= op1.size()) ans = op1;
				}
			}
		}
		//cout << ans << endl;
		cout << ans.size() << endl;
	}
	return 0;
}