您的位置:首页 > 其它

hdu 1238 & POJ 1226 Substrings

2012-08-09 16:34 399 查看
hdu题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1238

POJ题目链接:http://poj.org/problem?id=1226

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

*******************************************************************************************************************



题意:求最长公共子串。



方法:先找出最短的字符串,在此字符串上下手,从最长开始逐渐递减,直到找到为止。



代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define FOR(i,n) for(i=0;i<n;i++)

using namespace std;
int n;
char str[110][110];//存放全部字符串 
char st[110];//寻找最短字符串short 
char revs[110];//字串的倒置strrev 
char vs[110];//去比较吧, 

void strev(){//HDU和POJ都不能识别strrev所还得自己写. 
//如果可以的话,直接strrev(str)。 
	char sw[110];
	int i,tot=0;
	strcpy(sw,revs);
	for(i=strlen(sw)-1;i>=0;i--)
		revs[tot++]=sw[i];
	revs[tot]='\0';
}

int Find(){
	int lens=strlen(st),rlens=strlen(st),i,j;
	bool flag;
	while(lens){//从最长的开始找 
		for(i=0;i<=rlens-lens;i++){
			strncpy(vs,st+i,lens);
			strncpy(revs,st+i,lens);//第二个复制,用于下面的倒置 
			vs[lens]=revs[lens]='\0';//尾问处理 
			strev();//没有参数,但每次调用的作用都是倒置revs 
			flag=true;
			for(j=0;j<n;j++){//比较全部字符串 
				if(!strstr(str[j],revs)&&!strstr(str[j],vs)){//如果两个都没有、做下面 
					flag=false;
					break;
				}
			}
			if(flag) return lens;
		}
		lens--;
	}
	return lens;//可能一个也没有,返回0 
}
//主函数 
int main(){
	int t,i,x=110;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		x=110;
		FOR(i,n){
			scanf("%s",str[i]);
			if(strlen(str[i])<x){//寻找最短的字符串 
				x=strlen(str[i]);
				strcpy(st,str[i]);
			}
		}
		printf("%d\n",Find());
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: