题意:要从1到N的最短路并且每一条路上有对应的花费要求,总花费不能大于给定的一个值K,输出最短路径的长度.
方法: 不仅要最短,还有花费限制,所以就想到用优先队列,来维护一个优先级关系,使得答案最优.
AC代码:
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<set>
#include<queue>
#include<functional>
#include<vector>
#include<stack>
#include<map>
#include<cstdlib>
#define CLR(x) memset(x,0,sizeof(x))
#define ll long long int
#define PI acos(-1.0)
#define db double
#define mod 1000000007
using namespace std;
const int maxn = 1e4+5;
const int inf=1e9;
int k,n,r;
int cnt;
struct node
{
int to,w,c,next;
}s[maxn]; //模拟链表.
struct cmp //优先队列需要用.
{
int id,dis,cost;
bool operator < (const cmp &a) const { //以取&号的为准!
if(a.dis == dis ) return a.cost < cost ; //其次是花费小的优先.
return a.dis < dis ; //先让路最短的优先.
}
};
int head[maxn];
void add(int u,int v, int w,int c) //模拟过程.
{
s[cnt].to=v,s[cnt].w=w,s[cnt].c=c;
s[cnt].next=head[u];
head[u]=cnt++;
}
void dij() //dij + 优先队列优化!!! , 学会啊 !!!
{
priority_queue<cmp>q;
cmp a,b;
int res=inf;
a.id=1; //初始化情况
a.dis=0;
a.cost=0;
q.push(a);
while(!q.empty()){
b=q.top();
q.pop();
if(b.id == n){
res=b.dis; //已找到目标点,所以推出bfs.
break;
}
for(int i=head[b.id];i!=-1;i=s[i].next){
int to=s[i].to;
int w=s[i].w;
if(s[i].c + b.cost <= k){ //花费小于k.
a.id = to;
a.dis = b.dis + w;
a.cost = b.cost + s[i].c ;
q.push(a);
}
}
}
if(res == inf ) printf("-1\n");
else printf("%d\n",res);
}
int main()
{
scanf("%d %d %d",&k,&n,&r);
cnt=0;
memset(head,-1,sizeof(head));
for(int i=0;i<r;i++){
int u,v,w,c;
scanf("%d %d %d %d",&u,&v,&w,&c);
add(u,v,w,c); //单向边,所以只需要加一次.
}
dij();
}