hdu5067 状态压缩:经典旅行商问题

 1 #include<stdio.h>
 2 #include<string.h>
 3 int dp[1050][15],a[55][55],x[15],y[15],dist[15][15];
 4 int mabs(int x)
 5 {
 6     return x>0?x:-x;
 7 }
 8 int main()
 9 {
10     int n,m,cnt,i,j,k,s,minn,temp;
11     while (~scanf("%d%d",&n,&m))
12     {
13         cnt=-1;
14         for (i=1;i<=n;i++)
15             for (j=1;j<=m;j++)
16         {
17             scanf("%d",&a[i][j]);
18             if (a[1][1]) a[1][1]=0;
19             if (a[i][j]) {cnt++; x[cnt]=i; y[cnt]=j; }
20         }
21         if (cnt==-1) {printf("0\n"); continue; }
22         for (i=0;i<=cnt;i++)
23             for (j=0;j<=cnt;j++) dist[i][j]=mabs(x[i]-x[j])+mabs(y[i]-y[j]);
24         s=(1<<(cnt+1))-1;
25         memset(dp,0,sizeof(dp));
26         for (i=1;i<=s;i++)
27             for (j=0;j<=cnt;j++)
28             if ((i&(1<<j))!=0)
29         {
30             temp=i^(1<<j); minn=100000;
31             for (k=0;k<=cnt;k++)
32                 if ((temp&(1<<k))!=0)
33             {
34                 if (dist[k][j]+dp[temp][k]<minn) minn=dp[temp][k]+dist[k][j];
35             }
36             if (minn==100000) dp[i][j]=x[j]+y[j]-2;
37             else dp[i][j]=minn;
38         }
39         minn=100000;
40         for (i=0;i<=cnt;i++)
41             if (dp[s][i]+x[i]+y[i]-2<minn) minn=dp[s][i]+x[i]+y[i]-2;
42         printf("%d\n",minn);
43     }
44 }

http://acm.hdu.edu.cn/showproblem.php?pid=5067

posted on 2014-10-19 01:14  xiao_xin  阅读(125)  评论(0编辑  收藏  举报

导航