题意:给出m个字符串,找出其中的最长公共子序列,如果相同长度的有多个,输出按字母排序中的第一个。
思路:数据小,因此枚举第一个字符串的所有子字符串s,再一个个比较,是否为其它字符串的字串。判断是否为字串的时候,将s的字符依次与其他字符串的字符比较。
#include <iostream> #include <stdio.h> #include <string.h> #include <stack> #include <algorithm> using namespace std; const int maxm=15; const int maxlen=65; char str[maxm][maxlen]; //存储m个字符串 char s[maxlen],ans[maxlen]; //s存储枚举str[0]的子字符串,ans存储m个字符串序列的最长公共序列 int n,m; int len; //枚举子字符串的长度 //判断s是否为str[i]的子字符串 bool common(int i){ int flag; for(int j=0;j+len<=60;j++){ flag=1; for(int k=0;k<len;k++){ if(str[i][j+k]!=s[k]){ flag=0; break; } } if(flag) return 1; } return 0; } //判断子字符串是否为str[1]~str[m]的子字符串 bool isOk(){ for(int i=1;i<m;i++){ if(!common(i)){ return 0; } } return 1; } int main() { scanf("%d",&n); while(n--){ int maxl=0; scanf("%d",&m); for(int i=0;i<m;i++) scanf("%s",str[i]); for(len=3;len<=60;len++){ for(int i=0;i+len-1<60;i++){ strncpy(s,str[0]+i,len); //将str[0]的前len个字符拷贝到s中去 s[len]='