Hdu5067旅行商

题意:经历所有要求的点,最少距离。

诶 i==x的时候 continue了,fst 挂了。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <string>
#include <iostream>
#include <map>
#include <cstdlib>
#include <list>
#include <set>
#include <queue>
#include <stack>
#include <math.h>
using namespace std;
typedef long long LL;
const int INF = 0xfffffff;
int ret[100][100];
int dp[13][1 << 12];
int ans;
int abs(int x)
{
    return x>0 ? x : -x;
}

int gao(int x, int state)
{
    if (state == 0 && x == 0) return 0;
    if (~dp[x][state]) return dp[x][state];
    int sum = INF;
    for (int i = 0; i<ans; i++){
        if (state&(1 << i)){
            sum = min(sum, gao(i, state ^ (1 << i)) + ret[x][i]);
        }
    }
    return dp[x][state] = sum;
}

int main()
{
    int n, m;
    int Hash[100][100];
    int Map[100][100];
    while (cin >> n >> m){
        memset(dp, -1, sizeof(dp));
        ans = 1;
        memset(Hash, 0, sizeof(Hash));
        memset(ret, 0, sizeof(ret));
        for (int i = 0; i<n; i++){
            for (int j = 0; j<m; j++){
                scanf("%d", &Map[i][j]);
                if (i == 0 && j == 0) continue;
                if (Map[i][j]){
                    Hash[i][j] = ans++;
                    ret[0][ans - 1] = ret[ans - 1][0] = i + j;
                }
            }
        }
        if (ans == 1 && Map[0][0]){
            printf("%d\n", 0);
            continue;
        }
        for (int i = 0; i<n; i++){
            for (int j = 0; j<m; j++){
                for (int k = 0; k<n; k++)
                for (int l = 0; l<m; l++){
                    if (Hash[i][j] && Hash[k][l]){
                        ret[Hash[k][l]][Hash[i][j]] = ret[Hash[i][j]][Hash[k][l]] = abs(i - k) + abs(j - l);
                    }
                }
            }
        }
        int k = gao(0, (1 << ans) - 1);
        printf("%d\n", k);
    }
    return 0;
}

 

posted on 2014-10-21 16:02  一个西瓜  阅读(163)  评论(0编辑  收藏  举报

导航