深度优先搜索:寻路问题
2017-12-03 本文已影响6人
cherryleechen
问题描述
![](https://img.haomeiwen.com/i8016875/0a27ea8fe46badf9.png)
解题思路
![](https://img.haomeiwen.com/i8016875/8a618731e84d3062.png)
程序实现
#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;
}
运行结果
![](https://img.haomeiwen.com/i8016875/a94ddd4e2f4c28d4.png)