深度优先搜索:寻路问题

原文地址:https://www.jianshu.com/p/12fa7f26ada9

问题描述

图1 问题描述

解题思路

图2 解题思路

程序实现

#include<iostream>
#include<cstring>
#include<vector>

using namespace std;

int K, N, R;
struct Road
{
    int des;
    int len;
    int cost;
    Road(int d, int l, int c): des(d), len(l), cost(c) {}
    Road() {}
};
const int MAXK = 10001;
const int MAXN = 101;
vector<vector<Road>> Roads(MAXN);
int totalLen = 0;
int totalCost = 0;
int minTotalLen = 1 << 30;
bool mark[MAXN];
int midL[MAXN][MAXK];

void DFS(int start, int end)
{
    if(start == end)
        {
            minTotalLen = min(minTotalLen, totalLen);
            return;
        }
    for(int i = 0; i < Roads[start].size(); i++)
        {
            int des = Roads[start][i].des;
            if(!mark[des])
                {
                    int len = Roads[start][i].len;
                    int cost = Roads[start][i].cost;
                    totalLen += len;
                    totalCost += cost;
                    mark[des] = true;
                    if((totalLen < minTotalLen) && (totalCost <= K) && (totalLen < midL[des][totalCost]))
                        {
                            midL[des][totalCost] = totalLen;
                            DFS(des, end);
                        }
                    totalLen -= len;
                    totalCost -= cost;
                    mark[des] = false;
                }
        }
}


int main()
{
    cin >> K;
    cin >> N;
    cin >> R;
    int tmpStart, tmpEnd, tmpLen, tmpCost;
    for(int i = 0; i < R; i++)
        {
            cin >> tmpStart >> tmpEnd >> tmpLen >> tmpCost;
            if(tmpStart != tmpEnd)
                Roads[tmpStart].push_back(Road(tmpEnd, tmpLen, tmpCost));
        }
    for(int i = 1; i <= N; i++)
        for(int j = 1; j <= K; j++)
            midL[i][j] = 1 << 30;
    memset(mark, 0, sizeof(mark));
    mark[1] = true;
    DFS(1, N);
    if(minTotalLen < (1 << 30)) cout << minTotalLen << endl;
    else cout << -1 << endl;
}

运行结果

图3 运行结果

猜你喜欢

转载自www.cnblogs.com/cherrychenlee/p/10889644.html