您的位置:首页 > 编程语言 > C语言/C++

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

2013-09-26 21:37 531 查看
#include<iostream>
#include<stack>
#include<stdlib.h>
using namespace std;

stack<char> s;//当前搜索路径的LCS
stack<char> lcs[100];//所有的LCS

int 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]
,b[m]
作为逆推的记录
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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 算法