好像状压DP也能搞,2^10的复杂度应该是比直接暴力40W的复杂度好很多,不减枝的话900ms,减枝可以优化到600ms.
有时间搞搞状压DP
#include<iostream>
#include<cstdio>
#include<set>
#include<string>
#include<string.h>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<cctype>
#include<algorithm>
#include<sstream>
#include<utility>
#include<cmath>
#include<functional>
#define mt(a) memset(a,0,sizeof (a))
#define fl(a,b,c) fill(a,b,c)
#define SWAP(a,b,t) (t=a,a=b,b=t)
#define inf 1000000000+7
using namespace std;
typedef long long ll;
class node
{
public:
int id;
int x, y;
bool operator<(const node &b)
{
return id < b.id;
}
};
int main()
{
int n, m;
while (cin >> n >> m)
{
int cot = 0;
node a[20];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
int num;
scanf("%d", &num);
if (num)
{
a[cot].id = cot;
a[cot].x = i;
a[cot].y = j;
cot++;
}
}
}
sort(a, a + cot);
int minn= 999999;
if (cot)
{
do
{
int ans = a[0].x + a[0].y;
for (int i = 1; i < cot; i++)
{
ans += (abs(a[i].x - a[i - 1].x) + abs(a[i].y - a[i - 1].y));
if (ans>minn)break;
}
ans += (a[cot - 1].x + a[cot - 1].y);
minn = min(ans, minn);
} while (next_permutation(a, a + cot));
}
else minn = 0;
printf("%d\n", minn);
}
return 0;
}