给定k元钱,要求满足在k元钱内的最短路。
虽然是最短路问题,但是由于它的限制条件,在设计算法时也无需更新最短路,因此采用Bfs与优先队列结合的算法,通过优先队列不断取出符合条件的“最短路”。
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 100 + 5;
struct City {
int num, toll, dist;
bool operator > (const City& a) const {
return dist > a.dist;
}
};
struct Edge {
int to, dist, toll;
};
int k, n, r;
vector<Edge> G[maxn];
int Bfs() {
priority_queue<City, vector<City>, greater<City> > q;
q.push((City){0, 0, 0});
while (!q.empty()) {
City c = q.top();
q.pop();
int u = c.num;
if (u == n - 1) {
return c.dist;
}
for (int i = 0; i < G[u].size(); i++) {
Edge e = G[u][i];
if (c.toll + e.toll <= k) {
q.push((City){e.to, c.toll + e.toll, c.dist + e.dist});
}
}
}
return -1;
}
int main(int argc, char const *argv[]) {
scanf("%d%d%d", &k, &n, &r);
for (int i = 0; i < r; i++) {
int s, d, l, t;
scanf("%d%d%d%d", &s, &d, &l, &t);
G[s-1].push_back((Edge){d-1, l, t});
}
printf("%d\n", Bfs());
return 0;
}