http://poj.org/problem?id=3270
Best Sequence
Time Limit: 1000MS |
| Memory Limit: 10000K |
Total Submissions: 4065 |
| Accepted: 1613 |
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
法一:
在数据并不是很大的情况下可以使用的办法;
一:匹配,这里的匹配统一为一个串的后缀另一个串的前缀进行匹配
二:按照数列的办法生成全排列,然后从中选出最小值
Source:(是仿照大神博客写的)
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int N=25;
char a[N][N];
int fail[N],p[N];
int save[N][N];
int n;
int min(int a,int b)
{
return a<b? a:b;
}
int pp(char s1[],char s2[])
{
int len1=strlen(s1);
int len2=strlen(s2);
for(int i=len1-len2;i<len1;i++)//从多余的部分算开始
{
int ok=1;
for(int j=i;j<len1;j++)
if(s1[j]!=s2[j-i])//每次都是从s2的第一个位置进行比较(因为要保证可以首位相连)
{
ok=0;
break;
}
if(ok)
{
printf("%d ",len1-len2);
return i-(len1-len2);
}
}
return len2;
}
int work()
{
for(int i=0;i<n;i++)
p[i]=i;
int ans = 0x3f3f3f3f;
do
{
int s=strlen(a[p[0]]);
for(int i=0;i<n-1;i++)
s+=save[p[i]][p[i+1]];//求以第p[i]为首的字符串相连的长度
ans=min(s,ans);
}while(next_permutation(p,p+n));//生成序号序列排列,这相当于搜索,从中找到组成串的最小值
return ans;
}
int main()
{
int T;
int i,j;
int ans;
int min;
int len1,len2;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%s",a[i]);
memset(save,0,sizeof(save));
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{ save[i][j]=pp(a[i],a[j]);//表示第j串加上第i个串之后的长度
//printf("%d ",save[i][j]);
}
}
//for(i=0;i<n;i++)
ans=work();
printf("%d\n",ans);
}
// system("pause");
return 0;
}