您的位置:首页 > 产品设计 > UI/UE

poj 1699—Best Sequence(dfs剪枝)

2017-02-10 20:15 429 查看
http://poj.org/problem?id=1699

Description

The twenty-first century is a biology-technology developing century. One of the most attractive and challenging tasks is on the gene project, especially on gene sorting program. Recently we know that a gene is made of DNA. The nucleotide bases from which DNA
is built are A(adenine), C(cytosine), G(guanine), and T(thymine). Given several segments of a gene, you are asked to make a shortest sequence from them. The sequence should use all the segments, and you cannot flip any of the segments. 

For example, given 'TCGG', 'GCAG', 'CCGC', 'GATC' and 'ATCG', you can slide the segments in the following way and get a sequence of length 11. It is the shortest sequence (but may be not the only one). 



Input

The first line is an integer T (1 <= T <= 20), which shows the number of the cases. Then T test cases follow. The first line of every test case contains an integer N (1 <= N <= 10), which represents the number of segments. The following N lines express N segments,
respectively. Assuming that the length of any segment is between 1 and 20.
Output

For each test case, print a line containing the length of the shortest sequence that can be made from these segments.
Sample Input
1
5
TCGG
GCAG
CCGC
GATC
ATCG

Sample Output
11

题目大意:有一些DNA序列,通过连接组合,组成最短的序列,如果一个序列的头部和另一个序列的尾部的字符串相同的话,那么这相同的一部分算一个长度,如图所示
基本思路:遍历每一个字符串,另一个字符串作为第一个,然后dfs找最优的,稍作剪枝,因为序列的最长度是确定的,切如果找出一个比较小的后,找dfs时比这个数小的就不用在遍历了

在这里可以预先处理一下任意两个字符串相连接时所增加的长度

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>

using namespace std;

int len[15];
int vis[15];
char s[15][250];

int addlen1[15][15];
int n;
int ans;
void add1(int x,int y)
{
// cout<<"----------------------"<<endl;
// cout<<"**"<<s[x]<<endl<<s[y]<<endl;
int v=len[x];
for(int i=0;i<len[x];i++)
{
int j=i,k=0;
while(j<len[x]&&k<len[y])
{
if(s[x][j]!=s[y][k])break;
j++;
k++;
}
if(j>=len[x])
{
v=i;
break;
}
}
int d=len[x]-v;
int ad=len[y]-d;
if(ad<0)ad=0;
addlen1[x][y]=ad;
//cout<<ad<<endl;
}

void dfs(int x,int d,int sum)
{
if(d>=ans)return ;///剪枝
if(sum==n)
{
//cout<<"d = "<<d<<endl;
if(d<ans)ans=d;
return ;
}
for(int i=0; i<n; i++)
{
if(vis[i]==0)
{
vis[i]=1;
dfs(i,d+addlen1[x][i],sum+1);
vis[i]=0;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%s",s[i]);
len[i]=strlen(s[i]);
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
add1(i,j);
}
}
ans=20*10+10;
memset(vis,0,sizeof(vis));
for(int i=0; i<n; i++) ///以第i个为起点
{
vis[i]=1;
dfs(i,len[i],1);
vis[i]=0;
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: