#include <bits/stdc++.h>
using namespace std;
int n, m, tot = 1, s, t, mincost, maxflow;
const int N = 1005, inf = 0x3f3f3f3f;
int head[N], to[N], nt[N], val[N], cost[N], dis[N], flow[N], last[N], pre[N],
    vis[N], A[N];
queue<int> q;
void add(int x, int y, int z, int w) {
  to[++tot] = y;
  val[tot] = z;
  cost[tot] = w;
  nt[tot] = head[x];
  head[x] = tot;
  to[++tot] = x;
  val[tot] = 0;
  cost[tot] = -w;
  nt[tot] = head[y];
  head[y] = tot;
}
int SPFA() {
  int x;
  for (int i = 1; i <= t; ++i) dis[i] = flow[i] = inf;
  dis[s] = 0;
  vis[s] = 1;
  q.push(s);
  pre[t] = -1;
  while (!q.empty()) {
    x = q.front();
    q.pop();
    vis[x] = 0;
    for (int i = head[x]; i; i = nt[i])
      if (val[i] && dis[to[i]] > dis[x] + cost[i]) {
        dis[to[i]] = dis[x] + cost[i];
        pre[to[i]] = x;
        last[to[i]] = i;
        flow[to[i]] = min(flow[x], val[i]);
        if (!vis[to[i]]) q.push(to[i]), vis[to[i]] = 1;
      }
  }
  return pre[t] != -1;
}
void MFMC() {
  while (SPFA()) {
    mincost += dis[t] * flow[t];
    maxflow += flow[t];
    int now = t;
    while (now != s) {
      val[last[now]] -= flow[t];
      val[last[now] ^ 1] += flow[t];
      now = pre[now];
    }
  }
}
int main() {
  cin >> n >> m;
  s = n + 1;
  t = n + 2;
  for (int i = 1, x, y, c, f; i <= m; ++i) {
    scanf("%d%d%d%d", &x, &y, &c, &f);
    if (c < f) {
      mincost += f - c;
      add(y, x, f - c, 0);
      add(y, x, c, 1);
    } else {
      add(x, y, c - f, 1);
      add(y, x, f, 1);
    }
    add(x, y, inf, 2);
    A[x] -= f;
    A[y] += f;
  }
  add(n, 1, inf, 0);
  for (int i = 1; i <= n; ++i)
    if (A[i] > 0)
      add(s, i, A[i], 0);
    else
      add(i, t, -A[i], 0);
  MFMC();
  cout << mincost;
  return 0;
}
