#include <bits/stdc++.h>
using namespace std;
const int N = 10005;
const int inf = 0x3f3f3f3f;
int m, n, k, cnt, S, T, cc[N], c[N], pre[N], prd[N], tot;
bool bo[N];
std::vector<int> Eid[N];
struct Edge {
  int c, w, v;
} E[N];
void AddEdge(int x, int y, int c, int w) {
  E[++cnt].v = y;
  E[cnt].c = c;
  E[cnt].w = w;
  Eid[x].push_back(cnt);
  E[++cnt].v = x;
  E[cnt].c = -c;
  E[cnt].w = 0;
  Eid[y].push_back(cnt);
}
bool spfa() {
  static int Q[N * 2];
  int ql, qr;
  Q[ql = qr = 0] = S;
  std::fill(c, c + T + 1, inf);
  cc[T] = 0;
  cc[S] = inf;
  c[S] = 0;
  while (ql <= qr) {
    int x = Q[ql++];
    bo[x] = 0;
    for (int i = 0; i < Eid[x].size(); i++) {
      const Edge &e = E[Eid[x][i]];
      if (e.w && e.c + c[x] < c[e.v]) {
        if (!bo[e.v]) Q[++qr] = e.v;
        bo[e.v] = 1;
        c[e.v] = e.c + c[x];
        cc[e.v] = min(e.w, cc[x]);
        pre[e.v] = x;
        prd[e.v] = Eid[x][i];
      }
    }
  }
  return cc[T] > 0;
}
int MaxFlow() {
  int flow = 0, cost = 0;
  while (spfa()) {
    int k = T;
    while (k != S) {
      E[prd[k]].w -= cc[T];
      E[prd[k] ^ 1].w += cc[T];
      k = pre[k];
    }
    flow += cc[T];
    cost += cc[T] * c[T];
  }
  return cost;
}
int in[N], out[N], ans;
int main() {
  cnt = -1;
  scanf("%d%d", &n, &m);
  T = n + 1;
  for (int i = 1; i <= m; i++) {
    int u, v, c, f;
    scanf("%d%d%d%d", &u, &v, &c, &f);
    in[v] += f;
    out[u] += f;
    if (f > c) {
      ans += f - c;
      AddEdge(u, v, 2, inf);
      AddEdge(v, u, 0, f - c);
      AddEdge(v, u, 1, c);
    } else {
      AddEdge(u, v, 1, c - f);
      AddEdge(u, v, 2, inf);
      AddEdge(v, u, 1, f);
    }
  }
  for (int i = 1; i <= n; i++)
    if (in[i] - out[i] > 0)
      AddEdge(0, i, 0, in[i] - out[i]);
    else
      AddEdge(i, T, 0, out[i] - in[i]);
  AddEdge(n, 1, 0, inf);
  cout << ans + MaxFlow();
}
