#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 5, inf = 1e9;
int t[N], fl[N], v[N], nxt[N], lst[N], l;
void add(int x, int y, int z, int c) {
  t[++l] = y;
  fl[l] = z;
  v[l] = c;
  nxt[l] = lst[x];
  lst[x] = l;
  t[++l] = x;
  fl[l] = 0;
  v[l] = -c;
  nxt[l] = lst[y];
  lst[y] = l;
}
int n, m, q[N], dis[N], pre[N], S, T, x, y, c, f, used[N], ans;
bool vis[N];
bool spfa() {
  for (int i = S; i <= T; i++) dis[i] = inf;
  dis[S] = 0;
  int i = 0, j = 1;
  q[1] = S;
  vis[S] = 1;
  while (i < j) {
    for (int k = lst[q[++i]]; k; k = nxt[k])
      if (fl[k] && dis[t[k]] > dis[q[i]] + v[k]) {
        dis[t[k]] = dis[q[i]] + v[k];
        pre[t[k]] = k;
        if (!vis[t[k]]) vis[t[k]] = 1, q[++j] = t[k];
      }
    vis[q[i]] = 0;
  }
  return dis[T] != inf;
}
int find() {
  int flow = inf;
  for (int x = T; x; x = t[pre[x] ^ 1]) flow = min(flow, fl[pre[x]]);
  for (int x = T; x; x = t[pre[x] ^ 1]) {
    fl[pre[x]] -= flow;
    fl[pre[x] ^ 1] += flow;
    ans += flow * v[pre[x]];
  }
}
int main() {
  scanf("%d%d", &n, &m);
  l = 1;
  S = 0;
  T = n + 1;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &x, &y, &c, &f);
    used[x] += f;
    used[y] -= f;
    if (c > f) {
      add(x, y, inf, 2);
      add(y, x, f, 1);
      add(x, y, c - f, 1);
    } else {
      ans += f - c;
      add(x, y, inf, 2);
      add(y, x, f - c, 0);
      add(y, x, c, 1);
    }
  }
  add(n, 1, inf, 0);
  for (int i = 1; i <= n; i++)
    if (used[i] > 0)
      add(i, T, used[i], 0);
    else
      add(S, i, -used[i], 0);
  while (spfa()) find();
  printf("%d\n", ans);
  return 0;
}
