Unidirectional TSP 【HDU - 1619】【DFS+记忆化搜索】

题目链接


  就是告诉你有三种走法,斜向上、向前、斜向下,问你从最左边的任一点出发抵达最右边,问所需要的最少权值是多少。


  我身边的人都告诉我说用DP来写,但是我一眼就觉得它是道DFS+记忆化搜索的题(不记忆化肯定会T,亲自实验过),然后我就直接敲了DFS,就过了,看代码吧,DFS可以说的不多。


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN=11;
int N, M, mp[maxN][maxN*10], pre[maxN][maxN*10], gain[maxN][maxN*10];
bool vis[maxN][maxN*10];
int dfs(int x, int y)
{
    if(vis[x][y]) return gain[x][y];
    if(y == M)
    {
        vis[x][y] = true;
        gain[x][y] = mp[x][y];
        return mp[x][y];
    }
    int ans=INF, tmp;
    if(x+1>N)
    {
        if( ans > (tmp=dfs(1, y+1)) )
        {
            pre[x][y] = 1;
            ans = tmp;
        }
    }
    if(x-1>0)
    {
        if( ans > (tmp=dfs(x-1, y+1)) )
        {
            pre[x][y] = x-1;
            ans = tmp;
        }
    }
    if( ans > (tmp=dfs(x, y+1)) )
    {
        pre[x][y] = x;
        ans = tmp;
    }
    if(x+1 <= N)
    {
        if( ans > (tmp=dfs(x+1, y+1)) )
        {
            pre[x][y] = x+1;
            ans = tmp;
        }
    }
    if(x-1 == 0)
    {
        if( ans > (tmp=dfs(N, y+1)) )
        {
            pre[x][y] = N;
            ans = tmp;
        }
    }
    vis[x][y] = true;
    gain[x][y] = ans+mp[x][y];
    return ans+mp[x][y];
}
int main()
{
    while(scanf("%d%d", &N, &M)!=EOF)
    {
        for(int i=1; i<=N; i++)
        {
            for(int j=1; j<=M; j++)
            {
                scanf("%d", &mp[i][j]);
            }
        }
        int ans = INF, tmp, pos=1;
        memset(vis, false, sizeof(vis));
        memset(pre, -1, sizeof(pre));
        memset(gain, INF, sizeof(gain));
        for(int i=1; i<=N; i++)
        {
            if( ans > (tmp=dfs(i, 1)) )
            {
                ans = tmp;
                pos = i;
            }
        }
        printf("%d", pos);
        int i=1;
        while(pre[pos][i]!=-1) { printf(" %d", pre[pos][i]); pos=pre[pos][i]; i++; }
        printf("\n%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41730082/article/details/83997504