HDU ACM 1238 Substrings
Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6004 Accepted Submission(s): 2657
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
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<cmath> 5 #include<algorithm> 6 #define SIZE 102 7 8 using namespace std; 9 10 typedef struct strType 11 { 12 char value[SIZE]; 13 int len; 14 }strType; 15 16 strType alpha[SIZE]; 17 char pos[SIZE], neg[SIZE]; 18 19 bool Traverse(int cur, int neglect, int n) 20 { 21 if(cur == neglect) return Traverse(cur+1, neglect, n); 22 if(cur == n) return true; 23 24 if(strstr(alpha[cur].value, pos) != NULL || strstr(alpha[cur].value, neg) != NULL) 25 return Traverse(cur+1, neglect, n); 26 else return false; 27 } 28 29 int main() 30 { 31 int t; 32 scanf("%d", &t); 33 while(t--) 34 { 35 int n, shortest, id; 36 scanf("%d", &n); 37 getchar(); 38 for(int i=0; i<n; ++i) 39 { 40 scanf("%s", alpha[i].value); 41 alpha[i].len = strlen(alpha[i].value); 42 if(!i) shortest = alpha[i].len, id = i; 43 else if(shortest > alpha[i].len) 44 { 45 shortest = alpha[i].len; 46 id = i; 47 } 48 } 49 int res = 0; 50 for(int i=alpha[id].len-1; i>=0; i--) 51 { 52 if(i+1 < res) break; 53 for(int j=0; j<=i; j++) 54 { 55 if(i-j+1 < res) break; 56 memcpy(pos, alpha[id].value+j, sizeof(char)*(i-j+1)); 57 neg[i-j+1] = pos[i-j+1] = '\0'; 58 for(int t=0; t<i-j+1; ++t) neg[i-j-t] = pos[t]; 59 if(Traverse(0, id, n)) 60 { 61 res = i-j+1; 62 if(res < i-j+1) res = i-j+1; 63 } 64 } 65 } 66 printf("%d\n", res); 67 } 68 return 0; 69 }
【解题思路】strstr函数的应用,有几种不可能的情况需要先处理掉,所以一开始得找最短的字符串里的子字符串,且当前子字符串的长度至少要大于当前的符合所有字符串的要求 的子字符串

更多内容请关注个人微信公众号 物役记 (微信号:materialchains)
作者:雪影蓝枫
本文版权归作者和博客园共有,欢迎转载,未经作者同意须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。


浙公网安备 33010602011771号