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 :
Notice that different roads may have the same source and destination cities. Output The first and the only line of the output should contain the total length of the shortest path from the city 1 to the city N whose total toll is less than or equal K coins.
If such path does not exist, only number -1 should be written to the output. 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 2 Sample Output 11 |
思路:使用优先队列,每次都取出先前状态中距离最短的状态,注意,入队的不是点也不是边,而是先前满足花费小于K的所有的可行状态,队列里面保存的是先前取的点的状态,这样每次弹出距离最小的状态进行更新,到最后得到的一定是满足距离最小且花费不大于K的解,一旦发现N点在状态中,就可以返回了,因为此时的状态就是最优状态,再弹出其他状态进行更新时结果肯定比此时的大,因为优先队列首先弹出的是最小距离的状态。
1 #include<iostream> 2 #include<queue> 3 #include<cstdio> 4 #include<cstring> 5 using namespace std; 6 #define MAX 105 7 #define INF 1 << 30 8 typedef struct{ 9 int to, next, toll, length; 10 }Node; 11 typedef struct Status{ 12 int length, toll, u; 13 friend bool operator < (Status a, Status b){ 14 return a.length > b.length; 15 } 16 }Status; 17 Node edge[MAX*MAX]; 18 int head[MAX]; 19 int K, N, R; 20 int spfa(int s, int t){ 21 priority_queue<Status>q; 22 Status node; 23 node.length = 0; 24 node.toll = 0; 25 node.u = s; 26 q.push(node); 27 while(!q.empty()){ 28 node = q.top(); 29 q.pop(); 30 if(node.u == t) return node.length; 31 for(int i = head[node.u];i != -1;i = edge[i].next){ 32 if(edge[i].toll + node.toll <= K){ 33 Status temp; 34 temp.toll = edge[i].toll + node.toll; 35 temp.u = edge[i].to; 36 temp.length = node.length + edge[i].length; 37 q.push(temp); 38 } 39 } 40 } 41 return -1; 42 } 43 44 int main(){ 45 int u, v, l, t; 46 /* freopen("in.c", "r", stdin); */ 47 while(~scanf("%d%d%d", &K, &N, &R)){ 48 memset(head, -1, sizeof(head)); 49 for(int i = 1;i <= R;i ++){ 50 scanf("%d%d%d%d", &u, &v, &l, &t); 51 edge[i].to = v; 52 edge[i].length = l; 53 edge[i].toll = t; 54 edge[i].next = head[u]; 55 head[u] = i; 56 } 57 printf("%d ", spfa(1, N)); 58 } 59 return 0; 60 }