Best Sequence
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
我的代码
回溯。唯一值得注意的是需要对所有核苷酸片段进行预处理,我采用的预处理方法是mer[i][j]=i片段尾部与j片段相接的重合核苷酸碱基数量。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int mer[11][11];
int visited[11];
int ans,temp;
int n;
char seg[11][25];
int merge(char a[],char b[])
{
int lena=strlen(a);
int lenb=strlen(b);
int minlen=min(lena,lenb);
int len=0;
for (int i=0;i<minlen;i++)
{
int flag=0;
for (int j=0;j<=i;j++)
{
if (a[lena-1-i+j]!=b[j])
{
flag=1;
break;
}
}
if (flag==0) len=i+1;
}
return len;
}
void dfs(int step,int temp,int fore)
{
if (temp>=ans) return;
if (step==n)
{
if(temp<ans) ans=temp;
return;
}
for (int i=0;i<n;i++)
{
if (visited[i]==0)
{
visited[i]=1;
int now=temp+strlen(seg[i])-mer[fore][i];
dfs(step+1,now,i);
visited[i]=0;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
memset(visited,0,sizeof(visited));
ans=10000;
for (int i=0;i<n;i++)
{
scanf(" %s",seg[i]);
}
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
if (i==j) continue;
mer[i][j]=merge(seg[i],seg[j]);
}
}
for (int i=0;i<n;i++)
{
visited[i]=1;
dfs(1,strlen(seg[i]),i);
visited[i]=0;
}
printf("%d\n",ans);
}
return 0;
}
反思
这题分类也是dp就离谱,它把预处理当成dp了吗?