#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
const int N = 66666;
inline int read(int x = 0, bool f = 0, char ch = getchar()) {
  for (; !isdigit(ch); ch = getchar()) f = ch == '-';
  for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48);
  return f ? -x : x;
}
int n, m, tot = 1, sum, SS, TT;
int fi[N], ne[N], to[N], w[N], f[N], dis[N], pre[N], du[N];
bool v[N];
vector<pair<int, int>> ve;
inline void add(int x, int y, int l, int r, int z) {
  du[x] -= l;
  du[y] += l;
  ne[++tot] = fi[x];
  to[fi[x] = tot] = y;
  f[tot] = r - l;
  w[tot] = z;
  ne[++tot] = fi[y];
  to[fi[y] = tot] = x;
  f[tot] = 0;
  w[tot] = -z;
}
bool spfa() {
  queue<int> s;
  s.push(SS);
  for (int i = 1; i <= TT; ++i) dis[i] = inf, pre[i] = 0;
  dis[SS] = 0;
  while (!s.empty()) {
    int x = s.front();
    s.pop();
    v[x] = 0;
    for (int i = fi[x]; i; i = ne[i])
      if (f[i] && dis[to[i]] > dis[x] + w[i]) {
        dis[to[i]] = dis[x] + w[i];
        pre[to[i]] = i;
        if (!v[to[i]]) v[to[i]] = true, s.push(to[i]);
      }
  }
  return dis[TT] < inf;
}
int main() {
  cin >> n >> m;
  for (int i = 1, x, y, c, f; i <= m; ++i) {
    cin >> x >> y >> c >> f;
    if (c >= f) {
      add(x, y, 0, c - f, 1);
      add(y, x, 0, f, 1);
      add(x, y, 0, inf, 2);
    } else {
      sum += f - c;
      add(y, x, 0, f - c, 0);
      add(y, x, 0, c, 1);
      add(x, y, 0, inf, 2);
    }
    add(x, y, f, f, 0);
  }
  add(n, 1, 0, inf, 0);
  SS = n + 1, TT = n + 2;
  for (int i = 1; i <= n; ++i)
    if (du[i] > 0)
      add(SS, i, 0, du[i], 0);
    else
      add(i, TT, 0, -du[i], 0);
  while (spfa()) {
    int tmp = 1e9;
    for (int i = pre[TT]; i; i = pre[to[i ^ 1]]) tmp = min(tmp, f[i]);
    for (int i = pre[TT]; i; i = pre[to[i ^ 1]])
      sum += w[i] * tmp, f[i] -= tmp, f[i ^ 1] += tmp;
  }
  cout << sum << endl;
  return 0;
}
