ROADS
Time Limit: 1000MS; Memory Limit: 65536K
Description
N cities named with numbers 1 … N are connected with one-way roads. Each road has two parameters associated with it : the road length and the toll that needs to be paid for the road (expressed in the number of coins).
Bob and Alice used to live in the city 1. After noticing that Alice was cheating in the card game they liked to play, Bob broke up with her and decided to move away - to the city N. He wants to get there as quickly as possible, but he is short on cash.
We want to help Bob to find the shortest path from the city 1 to the city N that he can afford with the amount of money he has.Input
The first line of the input contains the integer K, 0 <= K <= 10000, maximum number of coins that Bob can spend on his way.
The second line contains the integer N, 2 <= N <= 100, the total number of cities.The third line contains the integer R, 1 <= R <= 10000, the total number of roads.
Each of the following R lines describes one road by specifying integers S, D, L and T separated by single blank characters :
- S is the source city, 1 <= S <= N
- D is the destination city, 1 <= D <= N
- L is the road length, 1 <= L <= 100
- T is the toll (expressed in the number of coins), 0 <= T <=100
Notice that different roads may have the same source and destination cities.
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input
5
6
7
1 2 2 3
2 4 3 3
3 4 2 4
1 3 4 1
4 6 2 1
3 5 2 0
5 4 3 2Sample Output
11
题意:每条路有两个属性:长度与过路费。你有k个金币,求花费不超过 k 的最短路。
带限制的最短路。
把入队条件变为:金币够用。如此一来,队里的结点全是金币足够用的。由于是优先队列,故终点第一次出队之际,就是最短路出现之时。
下面是用dijkstra算法。
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
const int INF=0x3f3f3f3f;
struct S{
int to,l,pay;
S(int xx,int yy,int zz):to(xx),l(yy),pay(zz){}
bool operator <(const S &a)const{
if(a.l==l) return pay>a.pay;
else return l>a.l;
}
};
vector<S> a[107];
int d[107];
int main(){
int k,n,r; scanf("%d%d%d",&k,&n,&r);
for(int i=1;i<=n;++i) d[i]=INF;
while(r--){
int x,y,z,w;
scanf("%d%d%d%d",&x,&y,&z,&w);
a[x].push_back(S(y,z,w));
}
d[1]=0;
int ans=INF;
priority_queue<S> q;
q.push(S(1,0,0));
while(!q.empty()){
S now=q.top();q.pop();
if(now.to==n){ //终点出现了
ans=now.l;
break;
}
for(int i=0;i<a[now.to].size();++i){
int tto=a[now.to][i].to,L=a[now.to][i].l,P=a[now.to][i].pay;
if(P+now.pay<=k){ // 金币够用
q.push(S(tto,L+now.l,P+now.pay)); //更新 l 与 pay
}
}
}
ans==INF?printf("-1\n"):printf("%d\n",ans);
return 0;
}
这道题也有其他写法:DFS+剪枝、DP……