#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int res = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -f;
    ch = getchar();
  }
  while (isdigit(ch)) {
    res = res * 10 + ch - '0';
    ch = getchar();
  }
  return res * f;
}
namespace qiqi {
const int N = 2005, INF = 0x3f3f3f3f;
int n, m, s = N - 2, t = N - 1, cnt, ecnt = 1, head[N], dis[N], flow[N], pre[N],
          d[N];
bool vis[N];
queue<int> q;
struct Edge {
  int v, w, f, nxt;
} e[N];
inline void add(int u, int v, int w, int f) {
  e[++ecnt] = (Edge){v, w, f, head[u]};
  head[u] = ecnt;
  e[++ecnt] = (Edge){u, -w, 0, head[v]};
  head[v] = ecnt;
}
inline bool spfa(int s, int t) {
  memset(dis, flow[s] = INF, sizeof(dis));
  dis[s] = pre[t] = 0;
  q.push(s);
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    vis[u] = 0;
    for (int i = head[u], v = e[i].v; i; v = e[i = e[i].nxt].v)
      if (e[i].f && dis[v] > dis[u] + e[i].w) {
        dis[v] = dis[u] + e[i].w;
        flow[v] = min(flow[u], e[i].f);
        pre[v] = i;
        if (!vis[v]) {
          q.push(v);
          vis[v] = 1;
        }
      }
  }
  return pre[t];
}
inline int mcmf(int s, int t) {
  int res = 0, x;
  while (spfa(s, t)) {
    res += flow[t] * dis[t];
    x = t;
    while (x) {
      e[pre[x]].f -= flow[t];
      e[pre[x] ^ 1].f += flow[t];
      x = e[pre[x] ^ 1].v;
    }
  }
  return res;
}
void main() {
  cnt = n = read();
  add(n, 1, 0, INF);
  m = read();
  while (m--) {
    ++cnt;
    int u = read(), v = read(), c = read(), f = read();
    add(u, cnt, 1, INF);
    add(cnt, u, 1, INF);
    add(cnt, v, 1, INF);
    add(cnt, v, 0, c);
    d[cnt] += f;
    d[u] -= f;
  }
  for (int i = (1); i <= (cnt); ++i) {
    if (d[i] > 0) add(s, i, 0, d[i]);
    if (d[i] < 0) add(i, t, 0, -d[i]);
  }
  printf("%d\n", mcmf(s, t));
}
}  // namespace qiqi
int main() {
  qiqi::main();
  return 0;
}
