#include <bits/stdc++.h>
using std::cerr;
using std::endl;
inline int rd() {
  int x;
  scanf("%d", &x);
  return x;
}
const int N = 2333, INF = 1e9;
int n, m, det[N];
struct Graph {
  int to, nxt, flow, cost;
} G[N * 2];
int head[N], etot = 1;
inline void addedge(int x, int y, int f, int c) {
  G[++etot] = {y, head[x], f, c}, head[x] = etot;
  G[++etot] = {x, head[y], 0, -c}, head[y] = etot;
}
int S, T;
int dis[N], cur[N];
bool vis[N];
std::queue<int> que;
inline bool spfa() {
  for (int i = 0; i <= T; ++i) dis[i] = INF, cur[i] = head[i], vis[i] = 0;
  dis[S] = 0, que.push(S);
  while (!que.empty()) {
    int x = que.front();
    que.pop();
    vis[x] = 0;
    for (int i = head[x]; i; i = G[i].nxt) {
      int y = G[i].to;
      if (G[i].flow && dis[y] > dis[x] + G[i].cost) {
        dis[y] = dis[x] + G[i].cost;
        if (!vis[y]) {
          vis[y] = 1;
          que.push(y);
        }
      }
    }
  }
  return dis[T] < INF;
}
long long cost;
int dfs(int x, int mf) {
  if (x == T) return mf;
  int used = 0;
  vis[x] = 1;
  for (int &i = cur[x]; i; i = G[i].nxt) {
    int y = G[i].to;
    if (G[i].flow && !vis[y] && dis[y] == dis[x] + G[i].cost) {
      int tmp = dfs(y, std::min(mf - used, G[i].flow));
      G[i].flow -= tmp, G[i ^ 1].flow += tmp;
      cost += 1ll * tmp * G[i].cost;
      if ((used += tmp) == mf) break;
    }
  }
  vis[x] = 0;
  return used;
}
inline long long solve() {
  while (spfa()) dfs(S, INF);
  return cost;
}
int main() {
  n = rd(), m = rd();
  long long ans = 0;
  for (int i = 1; i <= m; ++i) {
    int x = rd(), y = rd(), c = rd(), f = rd();
    if (f <= c) {
      addedge(y, x, f, 1);
      addedge(x, y, c - f, 1);
    } else {
      ans += f - c;
      addedge(y, x, f - c, 0);
      addedge(y, x, c, 1);
    }
    addedge(x, y, INF, 2);
    det[y] += f, det[x] -= f;
  }
  S = 0, T = n + 1;
  for (int i = 1; i <= n; ++i) {
    if (det[i] > 0) addedge(S, i, det[i], 0);
    if (det[i] < 0) addedge(i, T, -det[i], 0);
  }
  addedge(n, 1, INF, 0);
  std::cout << ans + solve() << std::endl;
  return 0;
}
