hdu1238---Substrings,
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: 1239 1072 1401 1515 1180
先二分長度,然後枚舉這樣長度的子串,依次去匹配
/************************************************************************* > File Name: hdu1238.cpp > Author: ALex > Mail: zchao1995@gmail.com > Created Time: 2015年02月17日 星期二 15時07分41秒 ************************************************************************/#include <map>#include <set>#include <queue>#include <stack>#include <vector>#include <cmath>#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const double pi = acos(-1);const int inf = 0x3f3f3f3f;const double eps = 1e-15;typedef long long LL;typedef pair <int, int> PLL;const int N = 110;int next[N];char str[N];char S[N][N];char T[N];void get_next (){ next[0] = -1; int j = 0; int k = -1; int len = strlen (str); while (j < len) { if (k == -1 || str[j] == str[k]) { next[++j] = ++k; } else { k = next[k]; } }}bool MATCH (){ int len1 = strlen (T); int len2 = strlen (str); int i = 0; int j = 0; while (i < len1 && j < len2) { if (j == -1 || T[i] == str[j]) { ++i; ++j; } else { j = next[j]; } } return j == len2;}void BinSearch (int n){ int l = 1; int r = strlen (S[1]); int len = r; int mid; int ans = 0; while (l <= r) { mid = (l + r) >> 1; bool G = false; for (int i = 0; i <= len - mid; ++i) { for (int j = i; j < i + mid; ++j) { str[j - i] = S[1][j]; } str[mid] = '\0'; get_next (); bool flag = true; for (int j = 2; j <= n; ++j) { strcpy (T, S[j]); if (MATCH()) { continue; } int x = strlen (T); for (int k = 0; k < x / 2; ++k) { swap (T[k], T[x - k - 1]); } if (MATCH()) { continue; } else { flag = false; break; } } if (flag) { G = true; break; } } if (G) { l = mid + 1; ans = mid; } else { r = mid - 1; } } printf("%d\n", ans);}int main (){ int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%s", S[i]); } BinSearch(n); } return 0;}