码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1699 Best Sequence (DFS+预处理)

时间:2014-08-16 22:32:41      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:poj 1699   best sequence   dfs   the twenty-first cen   

题意:看那张图就一清二楚了吧, N个序列首位相连(相同的序列部分),得到最短的总序列。

题目链接:http://poj.org/problem?id=1699

~~~~

思路就是:将N个序列首尾相连能重合的长度求粗来。然后DFS枚举每种首尾相连的情况。


#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 22
#define INF 0x7fffffff
using namespace std;

int n,ans;
int f[N][N],vis[N],len[N];
char str[N][N];
void get(int x,int y)  //f[x][y],将y贴到x后面能减少的最大重复长度
{
    int i,j,l;
    for(l=len[y];l>0;l--)   //枚举长度
    {
        int ok=1;
        for(i=len[x]-l,j=0;i<len[x] && j<len[y];i++,j++)
        {
            if(i<0)    //~~
            {
                ok=0;
                break;
            }
            if(str[x][i]!=str[y][j])
            {
                ok=0;
                break;
            }
        }
        if(ok)
        {
            f[x][y]=l;
            return ;
        }
    }
    f[x][y]=0;
}
void dfs(int x,int s,int tot)
{
    if(s==n)
    {
        ans=min(ans,tot);
        return ;
    }
    if(tot>ans)    //剪枝~
        return ;
    for(int i=0;i<n;i++)
    {
        if(!vis[i])
        {
            vis[i]=1;
            dfs(i,s+1,tot+len[i]-f[x][i]);  //~~
            vis[i]=0;
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%s",str[i]);
            len[i]=strlen(str[i]);
        }
        memset(f,0,sizeof(f));
        memset(vis,0,sizeof(vis));
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(i==j) continue;
                else get(i,j);
            }
        }
        ans=INF;
        for(int i=0;i<n;i++)    //dfs枚举每种首尾相连的方法。
        {
            vis[i]=1;
            dfs(i,1,len[i]);
            vis[i]=0;
        }
        printf("%d\n",ans);
    }
    return 0;
}


POJ 1699 Best Sequence (DFS+预处理),布布扣,bubuko.com

POJ 1699 Best Sequence (DFS+预处理)

标签:poj 1699   best sequence   dfs   the twenty-first cen   

原文地址:http://blog.csdn.net/darwin_/article/details/38619075

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!