#include <bits/stdc++.h>
using namespace std;
const int N = 1000005, inf = 1e9;
int h[N], nxt[N], adj[N], w[N], S, T, n, dlt[N], c[N], t = 1, m;
long long ans;
namespace MXF {
int a[N], d[N], pre[N], q[N], top1, top2, S, T;
bool inq[N];
inline int Min(const int p, const int q) { return p < q ? p : q; }
inline bool spfa() {
  register int i, top, j;
  for (i = 1; i <= T; ++i) a[i] = pre[i] = inq[i] = 0, d[i] = inf;
  top1 = top2 = 0, d[S] = 0, a[S] = inf, q[++top2] = S;
  while (top1 < top2) {
    top = q[++top1], inq[top] = false;
    for (i = h[top]; i; i = nxt[i]) {
      if (w[i] > 0 && d[j = adj[i]] > d[top] + c[i]) {
        d[j] = d[top] + c[i], a[j] = Min(a[top], w[i]), pre[j] = i;
        if (!inq[j]) inq[j] = 1, q[++top2] = j;
      }
    }
  }
  if (d[T] == inf) return 0;
  ans += (0ll + a[T]) * d[T];
  for (i = T; i ^ S; i = adj[pre[i] ^ 1])
    w[pre[i]] -= a[T], w[pre[i] ^ 1] += a[T];
  return 1;
}
inline void mcmf() {
  while (spfa())
    ;
}
}  // namespace MXF
inline void add(const int u, const int v, const int x, const int ci) {
  nxt[++t] = h[u], h[u] = t, adj[t] = v, w[t] = x, c[t] = ci, nxt[++t] = h[v],
  h[v] = t, adj[t] = u, w[t] = 0, c[t] = -ci;
}
int main() {
  scanf("%d%d", &n, &m), S = n + 1, T = S + 1;
  register int i, u, v, x, y;
  add(n, 1, inf, 0);
  for (i = 1; i <= m; ++i) {
    scanf("%d%d%d%d", &u, &v, &x, &y), add(u, v, inf, 2), dlt[u] -= y,
        dlt[v] += y;
    if (x >= y) add(v, u, y, 1), add(u, v, x - y, 1);
    if (x < y) ans += y - x, add(v, u, y - x, 0), add(v, u, x, 1);
  }
  for (i = 1; i <= n; ++i) {
    if (dlt[i] > 0) add(S, i, dlt[i], 0);
    if (dlt[i] < 0) add(i, T, -dlt[i], 0);
  }
  MXF::S = S, MXF::T = T, MXF::mcmf(), printf("%lld", ans);
  return 0;
}
