Best Sequence
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 5862 | Accepted: 2307 |
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).

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
给出长度不超过20的n(1<=n<=20)个字符串,求出一个字符串使得它们都是该字符串的子串,输出它可能的最小长度。
思路:
首先预处理一下y子串的以前一个是x子串时使用字符串的最少长度,就转化为排列问题,之后进行DFS即可。(无耻的借鉴了别人的思想)
#include <stdio.h> #include <string.h> #define min(a, b) a > b ? b : a char Map[15][22]; int a[15][22];//记录i连上j应该增加的长度 int vis[15]; int li[15]; int n, m; int cal( int x, int y)//计算增加的长度 { int len1 = strlen(Map[x]); int len2 = strlen(Map[y]); int b = -1; for( int i = 0, j; i < len1; i++) { for( j = 0; j < len2 && i + j < len1 ; j++) { if(Map[x][i+j] != Map[y][j]) { break; } } if( i + j >= len1) return len2 - j; } return len2; } int minlen; void dfs( int now, int cnt, int l) { if(l > minlen ) return; if(cnt == n) { minlen = min(minlen, l);return; } for( int i = 0; i < n; i++) { if(!vis[i]) { vis[i] = 1; dfs(i, cnt + 1, l + a[now][i]); vis[i] = 0; } } } int main() { int t; int i, j; while(~scanf("%d", &t)) { while(t--) { scanf("%d",&n); for( i = 0; i < n; i++) { scanf("%s", &Map[i]); li[i] = strlen(Map[i]); } for( i = 0; i < n; i++) { for( j = 0; j < n; j++) { if( i != j ) { a[i][j] = cal(i, j); //printf("%d--->%d:%d\n",i,j,a[i][j]); } } } memset(vis,0,sizeof(vis)); minlen = 0x3f3f3f3f; for( int i = 0; i < n; i++) { vis[i] = 1; dfs(i,1,li[i]); vis[i]=0; } printf("%d\n",minlen); } } }