/* 一個串的“子序列”(subsequence)是將這個串中的一些字符提取出來得到一個新串,並且不改變它們的相對位置關系。例如,串"XDoi","XianYu!","TaiQiangLa!","loa"都是串"XianYuDalaoTaiQiangLa!"的子序列。 我們說串t是串s1和s2的公共子序列,當且僅當t是s1的子序列且t是s2的子序列。定義串s1和s2的相似度為它們最長公共子序列的長度。 現在給定一個文本串S和一組模式串T[1]、T[2]、……、T[n]。求T[i]中和S具有最高相似度的那個,然后輸出最高的相似度。S和所有的T[i]都只含有小寫字母。 輸入規則:先是一行字符串S。第二行是n(1<=n<=100)。第三行以降的n行是n個模式串T[1]...T[n]。S和所有的T[i]的長度都不超過2000. Sample Input: abcdef 4 acfaff appont emmm bdxeuf Sample Output: bdxeuf 4 Description: 串abcdef和bdxeuf的最長公共子序列是bdef,長度為4. */ #include<iostream> #include<cstring> #include<algorithm> using namespace std; const int M=2010; int result[100]; /* void match(char *a,char *b,int s,int t,int i) { int x=s; int y=t; while(a[x]!='\0') { while(b[y]!='\0') { if(a[x]==b[y]) { result[i]++; match(a,b,x+1,y+1,i); cout<<b[y]<<endl; } y++; } x++; } } */ void match(char *a,char *b,int s,int t,int i) { int x=0; for(s=0;a[s]!='\0';s++) { for(t=x;b[t]!='\0';t++) { if(a[s]==b[t]) { result[i]++; x++; //cout<<b[t]<<endl; break; } } } } /* bool compare(int a,int b)//降序為> { return a>b; } */ int main() { char a[M]; char b[100][M]; memset(a,'\0',sizeof(a)); int n; while(scanf("%s",&a)) { memset(b,'\0',sizeof(b)); memset(result,0,sizeof(result)); cin>>n; for(int i=0;i<n;i++) scanf("%s",&b[i]); for(int i=0;i<n;i++) { match(a,b[i],0,0,i); //cout<<"result:"<<result[i]<<";"<<b[i]<<endl; } /* sort(result,result+n,compare); cout<<result[0]<<endl; memset(a,'\0',sizeof(a)); */ int max=result[0]; int max_num=0; for(int i=1;i<n;i++) { if(result[i]>max) { max_num=i; max=result[i]; } } cout<<b[max_num]<<endl<<max<<endl; memset(a,'\0',sizeof(a)); } return 0; }
代碼運行說明:

tz@HZAU
2019/3/7
