用动态规划法求解生物信息学中DNA序列比对的问题 (交叉学科应用实验)

来源:互联网 发布:w判断矩阵 编辑:程序博客网 时间:2024/06/08 04:22

#include<iostream>#include<stack>#include<stdlib.h>using namespace std;stack<char> s;//当前搜索路径的LCSstack<char> lcs[100];//所有的LCSint count=0;//记录LCS的数量bool lcs_have_exist(stack<char> lcs[],int count,stack<char> s){//判断当前搜索的LCS是否已存在于 stack_lcs[MAX]int i;bool exist=false;for (i=0;i<count;i++){if(lcs[i]==s){         exist=true; break;}}return exist;}void clear_stack(stack<char> &s){while(!s.empty()){s.pop();}}void out_stack()//输出栈s内容{stack<char> copy=s;cout<<count+1<<":";while(!copy.empty()){   cout<<copy.top()<<" ";copy.pop();}}void ALL_LCS(char X[],int b[][100],int i,int j){if(i==0||j==0)//当前搜索路径走到尽头{   if(!lcs_have_exist(lcs,count,s))//若当前搜索的LCS是新的LCS,则保存且输出{out_stack();cout<<endl;lcs[count]=s;count++;//增加一个LCS}}else if(i>0&&j>0){if(b[i][j]==3)//沿着对角线向上走{s.push(X[i]);ALL_LCS(X,b,i-1,j-1);s.pop();}else if(b[i][j]==1)//水平向左走{    ALL_LCS(X,b,i,j-1);}    else if(b[i][j]==2)//垂直向上走{            ALL_LCS(X,b,i-1,j);}    else if(b[i][j]==4)//先向左走,再向右{    ALL_LCS(X,b,i,j-1);ALL_LCS(X,b,i-1,j);}}}void LCS(char dna1[],char dna2[],int m,int n,int b[][100],int tag[][100]){//生成矩阵tag[m][n],b[m][n]作为逆推的记录int i,j,k;for(k=0;k<=m;k++) tag[k][0]=0;//初始化矩阵 for( k=0;k<=n;k++) tag[0][k]=0;for(i=1;i<=m;i++)for(j=1;j<=n;j++){if(dna1[i]==dna2[j]){tag[i][j]=tag[i-1][j-1]+1;b[i][j]=3;//"↖"}else if(tag[i][j-1]<tag[i-1][j]){                tag[i][j]=tag[i-1][j];b[i][j]=2;//"↑" }else if(tag[i][j-1]>tag[i-1][j]){  tag[i][j]=tag[i][j-1];b[i][j]=1;//"←"}else{tag[i][j]=tag[i][j-1];b[i][j]=4;//"←↑"}}for(i=0;i<=m;i++){    cout<<endl;    for(j=0;j<=n;j++){    cout<<tag[i][j]<<" ";}}}int main(){     const int max=100;//dna序列最大个数     char dna1[max]; char dna2[max];//定义dna int tag[max][max];//定义矩阵 int b[max][max];//记录轨迹 int i=1; int j=1; int k=0;     cout<<"请依次输入要比较的DNA序列(‘#’结束):"<<endl; cout<<"DNA1:"; cin>>dna1[i]; while(dna1[i]!='#') {  i++;      cin>>dna1[i]; } cout<<"DNA2:"; cin>>dna2[j];  while(dna2[j]!='#') {  j++;      cin>>dna2[j]; } cout<<endl;     cout<<"DNA1的序列:"; for(k=1;k<i;k++) {     cout<<dna1[k]<<"  ";//输入需要比较的DNA序列 } cout<<endl; cout<<"DNA2的序列:"; for( k=1;k<j;k++) {     cout<<dna2[k]<<"  "; } cout<<endl;    i--;j--;//剔除#号LCS(dna1,dna2,i,j,b,tag);    cout<<endl;cout<<"最长子序列:"<<endl;ALL_LCS(dna1,b,i,j);cout<<endl;return 0;}


原创粉丝点击