POJ--1699 Best Sequence(DP+dfs)

时间:2022-05-11
本文章向大家介绍POJ--1699 Best Sequence(DP+dfs),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Best Sequence Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 5543 Accepted: 2188 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 之所以说是DP,是因为这道题目实现把每两个字符串连接的状态保存起来,而后进行dfs遍历,最后选出最优值

#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h>

using namespace std;
char a[11][25];
int  dp[11][11];
int n;
int ans;
int vis[15];
void add(int m,int n)
{
    int k=0;
    int len1=strlen(a[m]);
    int len2=strlen(a[n]);
    bool tag;
    for(int p=1;p<=len1&&p<=len2;p++)
    {
        tag=true;
        for(int i=0,j=len1-p;i<p;i++,j++)
        {
            if(a[m][j]!=a[n][i])
            {
                tag=false;
                break;
            }
        }
        if(tag)
            k=p;
    }
    dp[m][n]=len2-k;
}
void dfs(int pre,int num,int sum)
{

    if(num==n)
    {

        if(ans>sum)
            ans=sum;
        return;
    }
    for(int i=0;i<n;i++)
    {
        if(vis[i]==0)
        {
            vis[i]=1;
            dfs(i,num+1,sum+dp[pre][i]);
            vis[i]=0;
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        getchar();
        for(int i=0;i<n;i++)
            scanf("%s",a[i]);
        memset(dp,0,sizeof(dp));
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                add(i,j);
        memset(vis,0,sizeof(vis));
        ans=9999;
        for(int i=0;i<n;i++)
        {
            vis[i]=1;
            dfs(i,1,strlen(a[i]));
            vis[i]=0;
        }
        printf("%dn",ans);

    }
    return 0;
}