#include <bits/stdc++.h>
using namespace std;
const int maxn = 1E5 + 5;
const int inf = 123456789;
int n, m;
struct info {
  int u, v, l, r, w;
};
namespace FLOW {
int size, head[maxn];
int S, T;
int dis[maxn];
struct edge {
  int to, next;
  int f, w;
} E[maxn * 2];
inline void init(int s, int t) {
  size = 1;
  S = s, T = t;
}
inline void addE(int u, int v, int f, int w) {
  E[++size].to = v;
  E[size].f = f;
  E[size].w = w;
  E[size].next = head[u];
  head[u] = size;
}
inline void add(int u, int v, int f, int w) {
  assert(S <= u && u <= T);
  assert(S <= v && v <= T);
  addE(u, v, f, w);
  addE(v, u, 0, -w);
}
bool vis[maxn];
int pre[maxn], maxF[maxn];
inline bool spfa() {
  for (int i = S; i <= T; ++i) dis[i] = inf, maxF[i] = inf;
  queue<int> Q;
  Q.push(S);
  dis[S] = 0;
  while (!Q.empty()) {
    int u = Q.front();
    Q.pop();
    vis[u] = 0;
    for (int i = head[u]; i; i = E[i].next) {
      if (E[i].f == 0) continue;
      int v = E[i].to, nw = dis[u] + E[i].w;
      if (nw < dis[v]) {
        dis[v] = nw;
        pre[v] = i;
        maxF[v] = min(maxF[u], E[i].f);
        if (!vis[v]) vis[v] = 1, Q.push(v);
      }
    }
  }
  return dis[T] != inf;
}
inline int MCMF() {
  int ans = 0;
  while (spfa()) {
    int pos = T, f = maxF[T];
    ans += f * dis[T];
    while (pos != S) {
      int id = pre[pos];
      E[id].f -= f;
      E[id ^ 1].f += f;
      pos = E[id ^ 1].to;
    }
  }
  return ans;
}
}  // namespace FLOW
int deg[maxn];
int main() {
  ios::sync_with_stdio(false);
  int ans = 0;
  cin >> n >> m;
  FLOW::init(0, n + 1);
  for (int i = 1; i <= m; ++i) {
    int u, v, c, f;
    cin >> u >> v >> c >> f;
    deg[u] -= f, deg[v] += f;
    if (c >= f) {
      FLOW::add(u, v, c - f, 1);
      FLOW::add(v, u, f, 1);
      FLOW::add(u, v, inf, 2);
    } else {
      ans += f - c;
      FLOW::add(v, u, f - c, 0);
      FLOW::add(v, u, c, 1);
      FLOW::add(u, v, inf, 2);
    }
  }
  for (int i = 1; i <= n; ++i) {
    if (deg[i] > 0)
      FLOW::add(0, i, deg[i], 0);
    else
      FLOW::add(i, n + 1, -deg[i], 0);
  }
  FLOW::add(n, 1, inf, 0);
  cout << ans + FLOW::MCMF() << endl;
  return 0;
}
