乘车路线

题目描述

  • 编号为 1\sim N N 座城镇用若干仅供单向行驶的道路相连,每条道路上均有两个参数:道路长度( length )和在该条道路上行驶的费用( cost )。
  • BOB 准备从城镇 1 出发到达城镇 N ,但他目前只有 W 的钱,为此,你需要帮助他寻找一条从城镇 1 到城镇 N 在他能支付的前提下的一条最短路线。

输入格式

  • W\ N\ M N 为城镇数目, 2<=N<=100 M 为道路条数, 1<=M<=10000,W 为钱的数目, 0<=W<=1000
  • 随后的 M 行每行为一条道路的信息,包含 4 个数值( u,v,w,cost ),表示从城镇 u v 有一条长度为 w 的单向道路,经过这条道路需要花费 cost 。( 1<=u,v<=N,1<=w<=100,0<=cost<=100

输出格式

输出最短长度,若无解,则输出“ NO ”;

样例

样例输入

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

样例输出

11

code

#include <bits/stdc++.h>
using namespace std;
const int maxn=100+10;
const int maxm=1e4+10;
const int INF=0x3f3f3f3f;
inline int read(){
	int k=0,f=1;char ch=getchar();
	for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-1;
	for(;isdigit(ch);ch=getchar()) k=k*10+ch-'0';
	return k*f;
}
struct edge{int to,dis,next,cost;}e[maxm];
struct node{
	int x,cost,dis;
	bool operator < (const node& a)const{
		return dis > a.dis;
	}
};
int cnt=0;int head[maxn];
inline int add(int u,int v,int w,int cost){e[++cnt]=(edge){v,w,head[u],cost},head[u]=cnt;}
int d[maxn][maxn],vis[maxn][maxn];int ans=INF;int W,N,M;
void Dij(){
	priority_queue<node>q;q.push((node){1,0,0});
	memset(d,0x3f,sizeof(d));d[1][0]=0;	
	while(!q.empty()){
		node tmp=q.top();q.pop();
		int x=tmp.x,cst=tmp.cost;
		if(vis[x][cst])continue;
		vis[x][cst]=1;
		if(x==N)if(cst<=W)ans=min(ans,d[x][cst]);
		for(int i=head[x];i;i=e[i].next){
			int v=e[i].cost+cst,u=e[i].to;
			if(v>W)continue;
			if(!vis[u][v] && d[u][v]>d[x][cst]+e[i].dis){
				d[u][v]=d[x][cst]+e[i].dis,	q.push((node){u,v,d[u][v]});
			}
		}
	}
}
int main(){
	W=read(),N=read(),M=read();int u,v,dis,cost;
	for(int i=1;i<=M;i++)
        u=read(),v=read(),dis=read(),cost=read(),add(u,v,dis,cost);
	Dij();
	if(ans==INF) return printf("NO\n"),0;
	else return printf("%d\n",ans),(0 ^ 0);
}

posted @ 2020-07-18 21:06  hyskr  阅读(136)  评论(0编辑  收藏  举报