[图论][最短路]ROADS

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

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
思路:dij的变形
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define inf 0x3f3f3f3f
using namespace std;

int k,n,m;
struct Edge{int v,len,cost;};
vector<Edge> edge[110];
struct Node{int v,dis,tot;};
bool operator <(Node a,Node b){return a.dis>b.dis;}
int ans[110];

void dijkstra(){
  memset(ans,0x3f,sizeof(ans));
  priority_queue<Node> q;q.push(Node{1,0,0});
  while(!q.empty()){
    Node now=q.top();q.pop();
    int u=now.v,dis=now.dis,tot=now.tot;
    if(tot>k) continue;
    ans[u]=dis;if(u==n) break;//其实ans没什么用,可以直接写成if(u==n) return dis;
    for(int i=0;i<(int)edge[u].size();i++){
        int v=edge[u][i].v,len=edge[u][i].len,cost=edge[u][i].cost;
        if(tot+cost<=k) q.push(Node{v,dis+len,tot+cost});//与普通的dijkstra有所不同,只要能走,就把这条边push进去,而不在乎是否能够松弛
    }
  }
}

int main()
{
   scanf("%d%d%d",&k,&n,&m);
   for(int i=1;i<=m;i++){
     int u,v,len,cost;scanf("%d%d%d%d",&u,&v,&len,&cost);
     edge[u].push_back(Edge{v,len,cost});
   }
   dijkstra();
   printf("%d\n",ans[n]==inf?-1:ans[n]);
}

猜你喜欢

转载自www.cnblogs.com/lllxq/p/9502505.html