Title: Harry and Dig Machine
haha finally rose edge pink, not easy ah. By the way, write a puzzle.
Test instructions: Give a m*n matrix, and then the maximum number of values from 10, the upper left corner of the total to take all the values back to the top left corner of the minimum steps.
The standard TSP back to the origin problem, it is necessary to preprocess the diagram first. Then the TSP can.
AC Code:
#include <cstdio> #include <algorithm> #include <cstring> #include <string> #include < iostream> #include <vector> #include <cmath>using namespace std;const int inf = 0x3f3f3f3f;const int N = 15;i NT mp[n][n];struct node{int x, y;}; Vector<node> vv;int n,m;int dp[1<<n][n];int main () {while (~scanf ("%d%d", &n,&m)) {for (int i=0;i<n;i++) {for (int j=0;j<m;j++) {int x; scanf ("%d", &x); if (x) Vv.push_back ((Node) {i,j}); }} int okk = 0; for (int i=0;i<vv.size (); i++) {if (vv[i].x==0 && vv[i].y==0) {okk=1 ; Continue }} if (Okk==0) Vv.push_back ((Node) {0,0}); for (int i=0;i<vv.size (), i++) {for (int j=0;j<vv.size (); j + +) {Mp[i][j] = 0; if (i==j) continue; MP[I][J] = ABS (vv[i].x-vv[j].x) + ABS (VV[I].Y-VV[J].Y); }} int len = Vv.size (); n = len; for (int st=0;st< (1<<n), st++)//tsp {for (int i=0;i<n;i++) {if (s t& (1<<i)) ==0)//?0 continue; if (st== (1<<i)) {dp[st][i]=mp[0][i];continue; } Dp[st][i]=inf; for (int j=0;j<n;j++) {if (st& (1<<j)) && i!=j)//?1 {Dp[st][i]=min (dp[st&~ (1<<i)][j]+mp[j][i],dp[st][i]); }}}} int ans=inf; for (int i=0;i<n;i++) {ans=min (ans,dp[(1<<n) -1][i]+mp[i][0]); } printf ("%d\n", ans); Vv.clear (); } return 0;}
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Bestcoder Round #14 B title Harry and Dig machine "TSP"