标签:fun between rsh 一个 VID ret att OLE spl
3 2 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 3 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA 3 CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSample Output
no significant commonalities AGATAC CATCATCAT
感觉暴力可以,但是没有去写。想用kmp,但是又无从下手,就学习了一波操作。
首先暴力第一串的所有子串,然后再其他字符串里面找是否存在。技巧之一就是从长到短枚举。
暴力:
1 #include<iostream> 2 #include<stdio.h> 3 #include<string> 4 #include<set> 5 #include<vector> 6 using namespace std; 7 vector<string> t; 8 set<string> ss; 9 string s; 10 int _,n; 11 12 string fun() { 13 ss.clear(); 14 string str=t[0]; 15 bool flag; 16 for(int len=60;len>=3;len--) { 17 for(int ix=0;ix<=60-len;ix++) { 18 string temp=str.substr(ix,len); 19 flag=true; 20 for(int k=1;k<t.size();k++) { 21 if(t[k].find(temp)==-1) { 22 flag=false; 23 break; 24 } 25 } 26 if(flag) ss.insert(temp); 27 } 28 if(ss.size()) return *ss.begin(); 29 } 30 return "no significant commonalities"; 31 } 32 33 int main() { 34 // freopen("in","r",stdin); 35 for(scanf("%d",&_);_;_--) { 36 scanf("%d",&n); 37 for(int i=0;i<n;i++) { 38 cin>>s; 39 t.push_back(s); 40 } 41 cout<<fun()<<endl; 42 t.clear(); 43 } 44 45 }
kmp思想:不需要找第一个串的所有子串,只需枚举每一个后缀,去和其他字符串匹配就行了。其实这个匹配过程就好比所有子串进行匹配了。
1 #include<stdio.h> 2 #include<iostream> 3 #include<string> 4 #include<algorithm> 5 #include<vector> 6 using namespace std; 7 int _,n,Next[61]; 8 string s,strans; 9 vector<string> t; 10 11 void prekmp(string s) { 12 int len=s.size(); 13 int i,j; 14 j=Next[0]=-1; 15 i=0; 16 while(i<len) { 17 while(j!=-1&&s[i]!=s[j]) j=Next[j]; 18 if(s[++i]==s[++j]) Next[i]=Next[j]; 19 else Next[i]=j; 20 } 21 } 22 23 int kmp(string p,string t) { 24 int len=t.size(); 25 int i=0,j=0,res=-1; 26 while(i<len) { 27 while(j!=-1&&t[i]!=p[j]) j=Next[j]; 28 ++i;++j; 29 res=max(res,j); 30 } 31 return res; 32 } 33 34 35 int main() { 36 // freopen("in","r",stdin); 37 for(scanf("%d",&_);_;_--) { 38 scanf("%d",&n); 39 for(int i=0;i<n;i++) { 40 cin>>s; 41 t.push_back(s); 42 } 43 int ans=-1; 44 string str=t[0]; 45 for(int i=0;i<60;i++) { 46 string temp=str.substr(i,60-i); 47 prekmp(temp); 48 int maxx=60; 49 for(int j=1;j<t.size();j++) { 50 maxx=min(maxx,kmp(temp,t[j])); 51 } 52 if(maxx>ans) { 53 strans=temp.substr(0,maxx); 54 ans=maxx; 55 } else if(maxx==ans) { 56 string anstemp=temp.substr(0,maxx); 57 if(anstemp<strans) strans=anstemp; 58 } 59 } 60 if(strans.size()<3) cout<<"no significant commonalities"<<‘\n‘; 61 else cout<<strans<<‘\n‘; 62 t.clear(); 63 } 64 }
kuangbin专题十六 KMP&&扩展KMP POJ3080 Blue Jeans
标签:fun between rsh 一个 VID ret att OLE spl
原文地址:https://www.cnblogs.com/ACMerszl/p/10290154.html