HDU3538 A sample Hamilton path

Problem Description Give you a Graph,you have to start at the city
with ID zero.

Input The first line is n(1<=n<=21) m(0<=m<=3) The next n line show
you the graph, each line has n integers. The jth integers means the
length to city j.if the number is -1 means there is no way. If i==j
the number must be -1.You can assume that the length will not larger
than 10000 Next m lines,each line has two integers a,b (0<=a,b< n)
means the path must visit city a first. The input end with EOF.

Output For each test case,output the shorest length of the hamilton
path. If you could not find a path, output -1

经典题。
状压dp。
dp[k][p]表示走过的点状态为k,目前在p点的最短路径。
转移时用当前状态刷表,枚举下一个走到的点i,dp[k|(1 << i)][i]=min(dp[k|(1 << i)][i],dp[k][p]+map[p][i])。
初始状态dp[1][0]=0。
目标状态min{dp[(1<< n)-1][i]}。
对于限制条件,可以把每个点之前必须走到的点二进制表示bef[],然后合法的条件就是bef[i]==(k&bef[i])
其他限制条件见代码。
不能用memset,否则会MLE【我也不知道为什么】。

#include<cstdio>
#include<cstring>
int min(int x,int y)
{
    return x<y?x:y;
}
int dp[2100000][25],map[25][25],bef[25];
int main()
{
    int i,j,k,m,n,p,q,x,y,z,ans;
    bool ok;
    while (scanf("%d%d",&n,&m)==2)
    {
        for (i=0;i<n;i++)
          bef[i]=0;
        for (i=0;i<(1<<n);i++)
          for (j=0;j<n;j++)
            dp[i][j]=0x3f3f3f3f;
        for (i=0;i<n;i++)
          for (j=0;j<n;j++)
            scanf("%d",&map[i][j]);
        for (i=1;i<=m;i++)
        {
            scanf("%d%d",&x,&y);
            bef[y]|=(1<<x);
        }
        dp[1][0]=0;
        for (k=1;k<(1<<n);k++)
          for (p=0;p<n;p++)
            if (dp[k][p]<0x3f3f3f3f&&k&(1<<p))
              for (i=0;i<n;i++)
                if (map[p][i]!=-1&&(!(k&(1<<i)))&&(bef[i]==(k&bef[i])))
                  dp[k|(1<<i)][i]=min(dp[k|(1<<i)][i],dp[k][p]+map[p][i]);
        ans=0x3f3f3f3f;
        for (i=0;i<n;i++)
          ans=min(ans,dp[(1<<n)-1][i]);
        if (ans==0x3f3f3f3f) printf("-1\n");
        else printf("%d\n",ans);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值