题目链接:1724 -- ROADS
题面:

题意:有r条单向道路,每条路有一个过路费和时间,我只有k元,问走到n的最少时间
思路:用链式前向星存图,然后搜索遍历一遍。
两个剪枝:
1.如果花费超过k了直接返回。
2.如果走到某个点的时间超过最短时间就返回
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
using namespace std;
#define endl "\n"
#define pi pair<int, int>
#define ll long long
#define N 105
#define M 20005
int minn;
bool vis[105];
int h[N], to[M], nex[M], w[M], s[M];
int cnt;
void add(int u, int v, int a, int b){
to[cnt] = v;
nex[cnt] = h[u];
w[cnt] = a;
s[cnt] = b;
h[u] = cnt++;
}
void dfs(int x, int n, int d, int l, int k){
if(d > k){
return ;
}
if(l >= minn){
return ;
}
if(x == n){
minn = min(minn, l);
return ;
}
vis[x] = 1;
for(int i = h[x]; i != -1; i = nex[i]){
int v = to[i];
if(vis[v] == 0){
dfs(v, n, d + s[i], l + w[i], k);
}
}
vis[x] = 0;
}
int main(){
ios::sync_with_stdio(false);
int k, n, r;
while(cin >> k >> n >> r){
for(int i = 1; i <= n; i++){
vis[i] = 0;
h[i] = -1;
}
cnt = 0;
for(int i = 0; i < r; i++){
int a, b, c, d;
cin >> a >> b >> c >> d;
add(a, b, c, d);
}
minn = 2147483647;
dfs(1, n, 0, 0, k);
if(minn == 2147483647){
cout << -1 << endl;
}else{
cout << minn << endl;
}
}
return 0;
}
博客探讨了如何解决POJ-1724(ROADS)问题,利用链式前向星存储图,并通过搜索遍历找到从起点到终点的最少时间。在搜索过程中实施了两个剪枝策略:当费用超过预算k时终止,以及当到达某点的时间超过已知最短时间时返回。
2478

被折叠的 条评论
为什么被折叠?



