1 2 3 0
1 3 2 0
1 4 5 0
3 4 9 0
2 4 1 0
/**
* URL:http://acm.pku.edu.cn/JudgeOnline/problem?id=1724
* Author: OWenT
* 优先队列(STL)+BFS
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
#define inf 1000000
class node
{
public:
long pdl, d, ctm;//已走过的路长, 终点, 花费
friend bool operator<(node a,node b)
{
return a.pdl > b.pdl;
}
};
typedef struct
{
long d,l,t;
}road;
vector<road>rd[10005];//路
priority_queue<node>state;//STL 优先队列
int main()
{
long k,n,r,i,output = inf;
scanf("%ld %ld %ld", &k, &n, &r);
for(i = 0; i < r; i ++)
{
road tmpRd;
long s;
scanf("%ld %ld %ld %ld", &s, &tmpRd.d, &tmpRd.l, &tmpRd.t);
rd[s].push_back(tmpRd);
}
//初始化
node tmpNd;
tmpNd.ctm = tmpNd.pdl = 0;
tmpNd.d = 1;
state.push(tmpNd);
//BFS
while(!state.empty())
{
node nd = state.top();
state.pop();
long s = nd.d;
if(s == n)
{
output = nd.pdl;
break;
}
for(i = 0; i < rd[s].size(); i ++)
{
if(nd.ctm + rd[s][i].t <= k)
{
node ad;
ad.d = rd[s][i].d;
ad.ctm = nd.ctm + rd[s][i].t;
ad.pdl = nd.pdl + rd[s][i].l;
state.push(ad);
}
}
}
//输出,inf即为没有符合的情况
if(output >= inf)
printf("-1\n");
else
printf("%ld\n", output);
return 0;
}