//zkw費用流
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 20000 + 5;
const int INF = 0x7f7f7f7f;
int from[MAXN << 1], to[MAXN << 1], next[MAXN << 1], cap[MAXN << 1], cos[MAXN << 1];
int a[MAXN], q[MAXN], p[MAXN], d[MAXN], fst[MAXN], inq[MAXN];
int ecnt = 1;
inline void add(int f, int t, int c, int cc) {
from[++ecnt] = f;
to[ecnt] = t;
cap[ecnt] = c;
cos[ecnt] = cc;
next[ecnt] = fst[f];
fst[f] = ecnt;
}
int main() {
int s, t, n, m;
scanf("%d%d", &m, &n);
s = 1;
t = n;
for (int i = 1; i <= m; i++) {
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
add(a, b, c, d);
add(b, a, 0, -d);
}
int flow = 0, cost = 0;
while (true) {
memset(d, 0x7f, sizeof(d));
memset(inq, 0, sizeof(inq));
d[s] = 0;
inq[s] = 1;
p[s] = 0;
a[s] = INF;
int head = 0, tail = 0, cnt = 0;
q[tail++] = s;
while (head < tail) {
if (cnt > m)break;//minus circle
int u = q[head++];
inq[u] = 0;
for (int i = fst[u]; i; i = next[i]) {
if (cap[i] > 0 && d[to[i]] > d[u] + cos[i]) {
d[to[i]] = d[u] + cos[i];
p[to[i]] = i;
a[to[i]] = min(a[u], cap[i]);
if (!inq[to[i]]) {
q[tail++] = to[i];
inq[to[i]] = 1;
}
}
}
cnt++;
}
if (d[t] >= INF)break;
flow += a[t];
cost += d[t] * a[t];
for (int u = t; u != s; u = from[p[u]]) {
cap[p[u]] -= a[t];
cap[p[u] ^ 1] += a[t];
}
}
printf("%d\n", cost);
return 0;
}