杭电1238————简单枚举

来源:互联网 发布:淘宝怎么确认收货 编辑:程序博客网 时间:2024/05/10 09:28

Substrings

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


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
23ABCDBCDFFBRCD2roseorchid
 

Sample Output
22
这个题没什么好说的(但是我WA了四个多小时我也不知道错哪儿了,然后重写了之后就过了,我摔!)
其实还是有一点点小问题.........
1.如何截取一段子串(详见自己写的函数copy)
2.如何反转字符串(本来想用strrev来着...忘了怎么用了于是就手动实现了一下...)
3.判断是否为一个字符串的子串(strstr内置函数很好用,建议刚刚接触的多看一下 <string.h>里边的相关函数)
上代码 ....
#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>#define  maxn 120using namespace std;/*按照字符串长度升序排列*/ int cmp_len(const void *a,const void *b){int la = strlen((char*)a);int lb = strlen((char*)b);return la > lb;}void copy(char *sub,char *s,int i,int j){int count = 0;for( ; i <= j ; i++)sub[count++] = s[i];sub[count] = '\0';}void reverse(char *resub,char *sub){int len = strlen(sub);for(int i = len - 1 ; i >= 0 ;i --)resub[len-1-i] = sub[i];resub[len] = '\0';}int main(){int T,n,maxlen,i,j,k;char s[maxn][maxn];char sub[maxn],resub[maxn];scanf("%d",&T);while(T--){memset(s,0,sizeof(s));memset(sub,0,sizeof(sub));memset(resub,0,sizeof(resub));maxlen = 0;scanf("%d",&n);for(i = 0 ; i < n ; i++)scanf("%s",s[i]);qsort(s,n,sizeof(s[0]),cmp_len);/*按照长度从小到大排列*/for(i = 0 ; i < strlen(s[0]) ; i++){for(j = i  ; j < strlen(s[0]) ; j++ ){copy(sub,s[0],i,j);reverse(resub,sub);for(k = 1 ; k < n ; k++){if(strstr(s[k],sub) == NULL && strstr(s[k],resub) == NULL)break;/*只要有一个不是子串就跳出*/ }if(k == n)/*找到一个子串*/ {if(strlen(sub) > maxlen)maxlen = strlen(sub);}}}printf("%d\n",maxlen);}return 0;}
PS:其实一开始写的那个逻辑有点混乱导致我改都不会改了,这个比较精简明了一些。也算是给自己提个醒吧,先把逻辑框架搭好再动手,不要看着简单就瞎写了,最后还是苦了自己。


0 0