hdu5067 Harry And Dig Machine(裸TSP问题 状压dp )

来源:互联网 发布:网站怎么弄三级域名 编辑:程序博客网 时间:2024/05/16 05:00
As we all know, Harry Porter learns magic at Hogwarts School. However, learning magical knowledge alone is insufficient to become a great magician. Sometimes, Harry also has to gain knowledge from other certain subjects, such as language, mathematics, English, and even algorithm. 
  Dumbledore, the headmaster of Hogwarts, is planning to construct a new teaching building in his school. The area he selects can be considered as an n*m grid, some (but no more than ten) cells of which might contain stones. We should remove the stones there in order to save place for the teaching building. However, the stones might be useful, so we just move them to the top-left cell. Taking it into account that Harry learned how to operate dig machine in Lanxiang School several years ago, Dumbledore decides to let him do this job and wants it done as quickly as possible. Harry needs one unit time to move his dig machine from one cell to the adjacent one. Yet skilled as he is, it takes no time for him to move stones into or out of the dig machine, which is big enough to carry infinite stones. Given Harry and his dig machine at the top-left cell in the beginning, if he wants to optimize his work, what is the minimal time Harry needs to finish it?
Input
They are sever test cases, you should process to the end of file. 
For each test case, there are two integers n and m.(1n,m50)(1≤n,m≤50)
The next n line, each line contains m integer. The j-th number of ithith line a[i][j] means there are a[i][j] stones on the jthjth cell of the ithith line.( 0a[i][j]1000≤a[i][j]≤100 , and no more than 10 of a[i][j] will be positive integer).
Output
For each test case, just output one line that contains an integer indicate the minimal time that Harry can finish his job.
Sample Input
3 30 0 00 100 00 0 02 21 11 1
Sample Output
44
题意:到达所有非0点回到起点花费的最小时间
做法:
遍历所有点之后,在回到最初点,看到这里我们就能想到这是一个典型的TSP问题,我们把所有非0点抽出来重新建图,之后跑一边TSP 就出来了
下面上代码:
#include<stdio.h>#include<algorithm>#include<math.h>#include<string.h> #define inf 999999using namespace std;struct node {int x,y;}edg[11];int dp[11][1<<11];int dist[11][11];int main(){int n,m,te;while(scanf("%d%d",&n,&m)!=EOF){int cnt=0;for(int i=0;i<n;i++){for(int j=0;j<m;j++){scanf("%d",&te);if(te||(!i&&!j)){edg[cnt].x=i,edg[cnt++].y=j;//注意第一个点也要抽出来 }}}for(int i=0;i<cnt;i++){for(int j=0;j<cnt;j++){dist[i][j]=abs(edg[i].x-edg[j].x)+abs(edg[i].y-edg[j].y);//重新建图 }}memset(dp,inf,sizeof(dp));dp[0][0]=0;for(int state=0;state<(1<<cnt);state++){for(int j=0;j<cnt;j++){if(dp[j][state]==inf) continue;//dp[j][state]表示的状态是 他当前走到 j点,城市游历状态是state时的最小步数, for(int k=0;k<cnt;k++){if((1<<k)&state)continue;{dp[k][(1<<k)|state]=min(dp[k][(1<<k)|state],dp[j][state]+dist[j][k]);//从j点找到一个不属于当前state状态的k点进转移取最小值 }}}}int ans=inf;for(int i=0;i<cnt;i++)//记得还要回来,所以加上 当前点 到0点的距离 {ans=min(ans,dp[i][(1<<cnt)-1]+dist[i][0]);}printf("%d\n",ans);}}


原创粉丝点击