Blue Jeans poj3080

來源:互聯網
上載者:User

   字典樹!我的做法是將前n-1個串分成若干子串(長度大於2),然後存入字典樹,再將第n串也分成若干子串,進行匹配。

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;struct node{int count;//記錄子串的數目int cur;//記錄當前子串來自哪一原串(防止同一原串的相同子串重複記錄)node *next[26];}memory[1000000],*root;struct word{char s[65];bool operator<(const word &t)const{return strcmp(s,t.s)<0;}}ans[60];//最長公用子串可能有多種,所以要多記錄下來,然後按字典序排序int ptr,n;char str[65];node *build_node(){node *p=&memory[ptr++];for(int i=0;i<26;i++)p->next[i]=NULL;p->cur=-1;p->count=0;return p;}bool insert_tree(int s,int e,int id){int index;node *p=root;for(int i=s;i<=e;i++){index=str[i]-65;if(p->next[index]==NULL)p->next[index]=build_node();p=p->next[index];}if(id!=p->cur)//該子串在當前串中沒重複出現{p->cur=id;p->count++;if(p->count==n)return true;}return false;}int main(){int cnt,t;bool ok;scanf("%d",&t);while(t--){scanf("%d",&n);ptr=0;root=build_node();for(int i=0;i<n-1;i++)//先將前n-1個串分別分成若干子串,然後存在字典樹中{scanf("%s",str);for(int j=0;j<60;j++)for(int k=j+2;k<60;k++)insert_tree(j,k,i);}ok=false;scanf("%s",str);cnt=0;for(int len=60;len>2;len--){if(ok)break;for(int i=0;i+len-1<60;i++)if(insert_tree(i,i+len-1,n-1)){ok=true;int j;for(j=i;j<=i+len-1;j++)ans[cnt].s[j-i]=str[j];ans[cnt].s[j-i]='\0';}}if(!ok){printf("no significant commonalities\n");continue;}sort(ans,ans+cnt);printf("%s\n",ans[0].s);}return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.