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
#include
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;i0;
        for (i=0;i<(1<for (j=0;j0x3f3f3f3f;
        for (i=0;ifor (j=0;j"%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<for (p=0;pif (dp[k][p]<0x3f3f3f3f&&k&(1<for (i=0;iif (map[p][i]!=-1&&(!(k&(1<1<1<map[p][i]);
        ans=0x3f3f3f3f;
        for (i=0;i1<1][i]);
        if (ans==0x3f3f3f3f) printf("-1\n");
        else printf("%d\n",ans);
    }
}

你可能感兴趣的:(动态规划,hdu)