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 Source |
提示
题意:给出长度不超过20的n(1<=n<=20)个字符串,求出一个字符串使得它们都是该字符串的子串,输出它可能的最小长度。
思路:
首先预处理一下y子串的以前一个是x子串时使用字符串的最少长度,就转化为排列问题,之后进行DFS即可。(无耻的借鉴了别人的思想)
示例程序
Source Code
Problem: 1699 Code Length: 1419B
Memory: 388K Time: 47MS
Language: GCC Result: Accepted
#include <stdio.h>
#include <string.h>
int v[10],sum,add[10][10],num,len[10];
char s[10][21];
void init(int x,int y)
{
int i,i1,t=0,flag,i2;
for(i=1;len[x]>=i&&len[y]>=i;i++)
{
flag=1;
i2=len[x]-i;
for(i1=0;i>i1;i1++)
{
if(s[y][i1]!=s[x][i2])
{
flag=0;
break;
}
i2++;
}
if(flag==1)
{
t=i;
}
}
add[x][y]=len[y]-t;
}
void dfs(int deep,int t,int n,int num)
{
int i;
if(sum<=num)
{
return;
}
if(deep==n)
{
if(sum>num)
{
sum=num;
}
return;
}
for(i=0;n>i;i++)
{
if(v[i]==0)
{
v[i]=1;
dfs(deep+1,i,n,num+add[t][i]);
v[i]=0;
}
}
}
int main()
{
int t,n,i,i1,i2;
scanf("%d",&t);
for(i=1;t>=i;i++)
{
scanf("%d",&n);
sum=200;
for(i1=0;n>i1;i1++)
{
v[i1]=0;
scanf("%s",s[i1]);
len[i1]=strlen(s[i1]);
}
for(i1=0;n>i1;i1++)
{
for(i2=0;n>i2;i2++)
{
init(i1,i2); //预处理
}
}
for(i1=0;n>i1;i1++)
{
v[i1]=1;
dfs(1,i1,n,len[i1]);
v[i1]=0;
}
printf("%d\n",sum);
}
return 0;
}