POJ 3080 Blue Jeans (KMP+暴力)

題目鏈接

題意:Genographic項目是IBM與國家地理學會之間的研究合作伙伴關係,該合作伙伴正在分析數十萬貢獻者的DNA,以繪製地球的分佈圖。

作爲IBM研究人員,您的任務是編寫一個程序,該程序將在給定的DNA片段之間找到共同點,這些片段可以與單個調查信息相關聯以識別新的遺傳標記。

通過在分子中發現氮鹼基的順序列出DNA鹼基序列,可以注意到DNA鹼基序列。有四個鹼基:
腺嘌呤(A),胸腺嘧啶(T),鳥嘌呤(G)和胞嘧啶(C)。
6個鹼基的DNA序列可以表示爲TAGACC。

給定一組DNA鹼基序列,請確定出現在所有序列中的最長鹼基序列。

對於輸入中的每個數據集,輸出所有給定鹼基序列共有的最長鹼基子序列。如果最長的公共子序列的長度小於3個鹼基,則顯示字符串“no significant commonalities”。如果存在多個最長長度相同的子序列,則僅輸出按字典序最小的子序列。

分析:每個串長60,最多20個串,所以暴力枚舉第一個串的所有長度大於2的子串依次和剩下的串kmp匹配即可。

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
const double eps=1e-6;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int mod=1e9+7;
const int maxn=1010;

int nx[maxn];
void getnx(string x){
	int m=x.size();
	int i,j;
	j=nx[0]=-1;
	i=0;
	while (i<m){
		while (-1!=j && x[i]!=x[j]) j=nx[j];
		if (x[++i]==x[++j]) nx[i]=nx[j];
		else nx[i]=j;
	}
}
int kmp(string s, string t) { 
	int n=s.size();
	int m=t.size();
	int i=0,j=0;
	//getnx(t);
	while (i<n && j<m) {
		while (-1!=j && s[i]!=t[j]) j=nx[j];
		i++;
		j++;
	}
	if (j==m)
		return i-j;
	else return -1;
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int T;
	cin>>T;
	while (T--){
		int k;
		cin>>k;
		string s[20];
		string ans="-";
		bool tag=false;
		for (int i=0; i<k; i++) 
			cin>>s[i];
		getnx(s[0]);
		for (int len=60; len>=3; len--){
			for (int j=0; j+len<=60; j++){
				string t=s[0].substr(j,len);
				for (int u=1; u<k; u++){
					if (kmp(s[u],t)==-1) break;
					if (u==k-1){
						if (ans=="-") ans=t;
						ans=ans<t?ans:t;
						tag=true;
					}
				}
			}
			if (tag) break;
		}
		if (ans=="-") cout<<"no significant commonalities"<<endl;
		else cout<<ans<<endl;	
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章