//本质上是对所有1为起点的路径的穷举
//但是这个数字太大了,深度搜索很有可能超时
//所以使用广度优先搜索
//一般的广度搜索是选择步数最少者为优,然而这次要选择距离短为优
//所以使用了优先队列而非普通队列
//有一个要注意的:Notice that different roads may have the same source and destination cities.建立图时要注意哦
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int maxn = 107;
bool M[maxn][maxn];
typedef struct cell
{
int State[2];
}cell;
vector<cell> Map[maxn][maxn];
typedef struct node
{
bool Vis[maxn];
int last;
int dis;
int cost;
bool operator < (const node &b) const {
return dis>b.dis;
}
}node;
int main()
{
ios::sync_with_stdio(false);
int k, n, r;
cin >> k >> n >> r;
for (int i = 0; i<r; i++)
{
int s, d;
cell lc;
cin >> s >> d;
cin >>lc.State[0]>>lc.State[1];
M[s][d] = 1;
Map[s][d].push_back(lc);
}
//解题思路:
//由于步数!=距离所以不能用普通的宽度优先搜索,应该用优先队列宽度搜索
//在到达目的地时,在拓展过程中减掉所有超支的路径.最后到达的一定是
//最短且符合要求的
priority_queue<node> Q;
node start;
memset(start.Vis, 0, sizeof(start.Vis));
start.dis = 0;
start.Vis[1] = 1;
start.last = 1;
start.cost = 0;
Q.push(start);
int ans = -1;
while (!Q.empty())
{
node tn = Q.top();
Q.pop();
if (tn.last == n&&tn.cost<=k)
{
ans = tn.dis;
break;
}
for (int i = 1; i <= n; i++)
{
if (!tn.Vis[i] && M[tn.last][i])
{
for (int j = 0; j < Map[tn.last][i].size(); j++)
{
if (tn.cost + Map[tn.last][i][j].State[1] <= k)
{
node nn = tn;
nn.Vis[i] = 1;
nn.last = i;
nn.dis += Map[tn.last][i][j].State[0];
nn.cost += Map[tn.last][i][j].State[1];
Q.push(nn);
}
}
}
}
}
cout << ans << endl;
return 0;
}