【POJ1699】-Best Sequence 搜索剪枝

Time Limit: 1000MS Memory Limit: 10000K

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).

【POJ1699】-Best Sequence 搜索剪枝_第1张图片

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

POJ Monthly–2004.07.18

题意:给你一些字符串,判断可以组成的最短的字符串。

思路:mp[i][j]表示j字符串接在i字符串的后面会增长多少,那么我们枚举起点的字符串,计算最短的字符串的长度。

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

using namespace std;

char str[11][22];

int mp[11][11];

bool vis[11];

int n,ans;

int add(int s,int t)
{
    int len1 = strlen(str[s]);

    int len2 = strlen(str[t]);

    for(int i = 0,j;i<len1;i++)
    {
        for(j = 0;j<len2 &&i+j<len1;j++)
        {
            if(str[s][i+j] !=str[t][j]) break;
        }

        if(i+j == len1) return len2-j;
    }

    return len2;
}

void DFS(int u,int num,int len)
{
    if(len > ans) return ;//剪枝

    if(num == n)
    {
        ans = min(ans,len);

        return ;
    }

    for(int i = 0;i<n;i++)
    {
        if(!vis[i])
        {
            vis[i] = true;

            DFS(i,num+1,len+mp[u][i]);

            vis[i] = false;
        }
    }
}

int main()
{
    int T;

    scanf("%d",&T);

    while(T--)
    {
        scanf("%d",&n);

        for(int i = 0;i<n;i++)
            scanf("%s",str[i]);

        for(int i = 0;i<n;i++)//计算j接在i的后面的时候会增加多少。
            for(int j =0;j<n;j++)
                mp[i][j] = add(i,j);

        memset(vis,false,sizeof(vis));

        ans = 210;

        for(int i = 0;i<n;i++)
        {
            vis[i] = true;

            DFS(i,1,strlen(str[i]));

            vis[i]=false;
        }

        printf("%d\n",ans);
    }

    return 0;
}

你可能感兴趣的:(【POJ1699】-Best Sequence 搜索剪枝)