#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
vector<int>edge[212121], redge[212121];
unsigned long long sum[212121];
unsigned long long deg[212121], col[212121];
unsigned long long bk = 500;
int main() {
	unsigned long long n, m, A, B, C; scanf("%llu%llu%llu%llu%llu", &n, &m, &A, &B, &C);
	unsigned long long i, j;
	unsigned long long ret = 0;
	for (i = 1; i <= n; i++) {
		unsigned long long cnt;
		cnt = (n - i) * (n - i - 1) / 2;
		ret += cnt * (i-1) * A;
		cnt = (i - 1) * (n - i);
		ret += cnt * (i-1) * B;
		cnt = (i - 1) * (i - 2) / 2;
		ret += cnt * (i-1) * C;
	}
	for (i = 0; i < m; i++) {
		unsigned long long s, e; scanf("%llu%llu", &s, &e);
		if (s > e)swap(s, e);
		edge[s].push_back(e);
		redge[e].push_back(s);
		//i == s j == e k = 나머지
		unsigned long long cnt;
		if (e != n - 1) {
			cnt = (n - 1) - (e + 1) + 1;
			ret -= cnt * s * A;
			ret -= cnt * e * B;
			ret -= (n*(n - 1) / 2 - e*(e + 1) / 2) * C;
		}
		//i == s j == 나머지 k = e
		cnt = (e - 1) - (s + 1) + 1;
		if (cnt > 0) {
			ret -= cnt * s * A;
			ret -= ((e - 1) * e / 2 - s * (s + 1) / 2) * B;
			ret -= cnt * e * C;
		}
		//i == 나머지 j == s k = e
		if (s != 0) {
			cnt = s - 1 - 0 + 1;
			ret -= (s - 1) * s / 2 * A;
			ret -= cnt * s * B;
			ret -= cnt * e * C;
		}
	}
	for (i = 0; i < n; i++) {
		for (unsigned long long nxt : edge[i]) {
			sum[i] += nxt;
		}
	}
	for (i = 0; i < n; i++) {
		sort(edge[i].begin(), edge[i].end());
		sort(redge[i].begin(), redge[i].end());
	}
	for (i = 0; i < n; i++) {
		vector<int>LL;
		for (unsigned long long nxt : edge[i]) {
			unsigned long long cnt;
			cnt = edge[nxt].size();
			ret += cnt * i * A;
			ret += cnt * nxt * B;
			ret += sum[nxt] * C;
		}
		unsigned long long sz = edge[i].size();
		ret += sz * (sz - 1) / 2 * A * i;
		for (unsigned long long p = 0; p < edge[i].size(); p++) {
			unsigned long long cnt, nxt = edge[i][p];
			cnt = sz - p - 1;
			ret += cnt * nxt * B;
			cnt = p;
			ret += cnt * nxt * C;
		}
		sz = redge[i].size();
		ret += sz * (sz - 1) / 2 * C * i;
		for (unsigned long long p = 0; p < redge[i].size(); p++) {
			unsigned long long cnt, nxt = redge[i][p];
			cnt = sz - p - 1;
			ret += cnt * nxt * A;
			cnt = p;
			ret += cnt * nxt * B;
		}
	}

	for (i = 0; i < n; i++) {
		vector<int>vv;
		for (unsigned long long nxt : edge[i]) {
			col[nxt] = 1;
			if (edge[nxt].size() >= bk) {
				col[nxt] = 2;
				vv.push_back(nxt);
			}
		}
		for (unsigned long long nxt : edge[i]) {
			if (col[nxt] == 1) {
				for (unsigned long long nnxt : edge[nxt]) {
					if (col[nnxt]) {
						// i -> small -> (small & big)
						ret -= i * A + nxt * B + nnxt * C;
					}
				}
			}
			else {
				// i -> big -> nxt(big)
				for (unsigned long long v : vv) {
					if (lower_bound(redge[nxt].begin(), redge[nxt].end(), v) != redge[nxt].end()) {
						// i -> v -> nxt
						ret -= i * A + v * B + nxt * C;
					}
				}
			}

		}
		for (unsigned long long nxt : edge[i])col[nxt] = 0;
	}
	printf("%llu\n", ret);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
const int inf=INT_MAX;
int n,m,s,ans,now=1,w[N],v[N],c[N],nex[N],head[N];
void add(int x,int y,int co,int z){
	nex[++now]=head[x],w[now]=z;
	head[x]=now,v[now]=y,c[now]=co;
}
int vi[N],dis[N],way[N],bfe[N];
queue<int>que;
bool spfa(){
	for(int i=0;i<s;i++)	dis[i]=inf;
	que.push(s),dis[s]=0,way[s]=inf;
	while(!que.empty()){
		int x=que.front();
		que.pop(),vi[x]=1;
		for(int i=head[x];i;i=nex[i])
			if(w[i]&&dis[x]+c[i]<dis[v[i]]){
				dis[v[i]]=dis[x]+c[i];
				bfe[v[i]]=i^1,way[v[i]]=min(way[x],w[i]);
				if(!vi[v[i]])	que.push(v[i]),vi[v[i]]=1;
			}
	}
	return dis[0]!=inf;
}
int flow[N];
int main(){
	//freopen("1.in","r",stdin);
	scanf("%d%d",&n,&m),s=n+1;
	for(int i=1,x,y,c,f;i<=m;i++){
		scanf("%d%d%d%d",&x,&y,&c,&f);
		flow[x]-=f,flow[y]+=f;
		if(c<f){
			ans+=f-c;
			add(x,y,2,inf),add(y,x,-2,0);
			add(y,x,1,f-c),add(x,y,-1,0);
			add(y,x,2,inf),add(x,y,-2,0);
		}
		else{
			add(x,y,2,inf),add(y,x,-2,0);
			add(y,x,1,inf),add(x,y,-1,0);
			if(c!=f)	add(x,y,1,c-f),add(y,x,-1,0);
		}
	}
	add(1,n,0,inf);
	for(int i=2;i<n;i++)
		if(flow[i]>0){
			add(i,0,0,flow[i]),add(0,i,0,0);
			add(s,n,0,flow[i]),add(n,s,0,0);
		}
		else	if(flow[i]<0){
			add(s,i,0,-flow[i]),add(i,s,0,0);
			add(1,0,0,-flow[i]),add(0,1,0,0);
		}
	/*for(int i=1;i<=n+3;i++){
		cout<<i<<endl;
		for(int j=head[i];j;j=nex[j])
			cout<<v[j]<<' '<<w[j]<<' '<<c[j]<<endl;
	}*/
	while(spfa()){
		int x=0;
		while(x!=s){
			w[bfe[x]]+=way[0];
			w[bfe[x]^1]-=way[0];
			x=v[bfe[x]];
		}
		ans+=way[0]*dis[0];
	}
	printf("%d\n",ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
const int inf=INT_MAX;
int n,m,s,ans,now=1,w[N],v[N],c[N],nex[N],head[N];
void add(int x,int y,int co,int z){
	nex[++now]=head[x],w[now]=z;
	head[x]=now,v[now]=y,c[now]=co;
}
int vi[N],dis[N],way[N],bfe[N];
queue<int>que;
bool spfa(){
	for(int i=0;i<s;i++)	dis[i]=inf;
	que.push(s),dis[s]=0,way[s]=inf;
	while(!que.empty()){
		int x=que.front();
		que.pop(),vi[x]=0;
		for(int i=head[x];i;i=nex[i])
			if(w[i]&&dis[x]+c[i]<dis[v[i]]){
		//cerr<<x<<' '<<dis[x]<<' '<<v[i]<<' '<<dis[v[i]]<<' '<<c[i]<<' '<<w[i]<<endl;
				dis[v[i]]=dis[x]+c[i];
				bfe[v[i]]=i^1,way[v[i]]=min(way[x],w[i]);
				if(!vi[v[i]])	que.push(v[i]),vi[v[i]]=1;
			}
	}
	return dis[0]!=inf;
}
int flow[N];
int main(){
	scanf("%d%d",&n,&m),s=n+1;
	for(int i=1,x,y,c,f;i<=m;i++){
		scanf("%d%d%d%d",&x,&y,&c,&f);
		flow[x]-=f,flow[y]+=f;
		if(c<f){
			ans+=f-c;
			add(x,y,2,inf),add(y,x,-2,0);
			add(y,x,0,f-c),add(x,y,0,0);
			add(y,x,2,c),add(x,y,-2,0);
		}
		else{
			add(y,x,1,f),add(x,y,-1,0);
			add(x,y,2,inf),add(y,x,-2,0);
			if(c!=f)	add(x,y,1,c-f),add(y,x,-1,0);
		}
	}
	add(s,1,0,inf),add(1,s,0,0);
	add(n,0,0,inf),add(0,n,0,0);
	add(n,1,0,inf),add(1,n,0,0);
	for(int i=2;i<n;i++)
		if(flow[i]<0){
			add(i,0,0,-flow[i]),add(0,i,0,0);
			add(s,n,0,-flow[i]),add(n,s,0,0);
		}
		else	if(flow[i]>0){
			add(s,i,0,flow[i]),add(i,s,0,0);
			add(1,0,0,flow[i]),add(0,1,0,0);
		}
	/*for(int i=1;i<=n+3;i++){
		cout<<i<<endl;
		for(int j=head[i];j;j=nex[j])
			cout<<v[j]<<' '<<w[j]<<' '<<c[j]<<endl;
	}*/
	//for(int j=head[4];j;j=nex[j])
	//	cout<<v[j]<<' '<<w[j]<<' '<<c[j]<<endl;
	while(spfa()){
		//cerr<<"is"<<endl;
		int x=0;
		//cout<<"is "<<dis[x]<<' '<<way[x]<<endl;
		while(x!=s){
			w[bfe[x]]+=way[0];
			w[bfe[x]^1]-=way[0];
			x=v[bfe[x]];
			//cout<<x<<' ';
		}
		//cerr<<"end"<<endl;
		//cout<<endl;
		ans+=way[0]*dis[0];
	}
	printf("%d\n",ans);
	return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <queue>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <bitset>

using namespace std;

#define fr first
#define sc second
#define mp make_pair
#define pb push_back
#define epr(...) fprintf(stderr, __VA_ARGS__)
#define db(x) cerr << #x << " = " << x << endl
#define db2(x, y) cerr << "(" << #x << ", " << #y << ") = (" << x << ", " << y << ")\n";
#define db3(x, y, z) cerr << "(" << #x << ", " << #y << ", " << #z << ") = (" << x << ", " << y << ", " << z << ")\n"
#define all(a) (a).begin(), (a).end()

#define equal equalll
#define less lesss
const int N = 222;
const long long INF = 1e9 + 19;
const int ALF = 26;

struct Node {
    int next[ALF];
    int go[ALF];
    int p, pch;
    int cost;
    int link;
    Node() {
        memset(next, -1, sizeof(next));
        memset(go, -1, sizeof(go));
        cost = 0;
        link = -1;
    }
};

int n;
long long l;
int c[N];
char s[N];
int cur = 1;
Node data[N];
int dp[N * N* 2][N];
int dp2[N][N][N];

void add(char * s, int len, int cost) {
    int v = 0;
    for (int i = 0; i < len; i++) {
        int ch = s[i] - 'a';
        if (data[v].next[ch] == -1) {
            data[v].next[ch] = cur;
            data[cur].p = v;
            data[cur].pch = ch;
            cur++;
        }
        v = data[v].next[ch];
    }
    data[v].cost += cost;
}

void build() {
    queue < int > q;
    q.push(0);
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        if (v == 0 || data[v].p  == 0) {
            data[v].link = 0;
        }
        else {
            data[v].link = data[data[data[v].p].link].go[data[v].pch];
        }

        for (int i = 0; i < ALF; i++) {
            if (data[v].next[i] != -1) {
                data[v].go[i] = data[v].next[i];
                q.push(data[v].next[i]);
            }
            else {
                if (v == 0)
                    data[v].go[i] = 0;
                else
                    data[v].go[i] = data[data[v].link].go[i];
            }
        }
        data[v].cost += data[data[v].link].cost;
    }
}

void read() {
    scanf("%d%lld", &n, &l);
    for (int i = 0; i < n; i++)
        scanf("%d", &c[i]);
    for (int i = 0; i < n; i++) {
        scanf("%s", s);
        int len = strlen(s);
        add(s, len, c[i]);
    }
}

void upd(int & a, int b) {
    a = max(a, b);
}

void solve() {
    build();
    memset(dp, -63, sizeof(dp));
    dp[0][0] = 0;

    for (int i = 0; i < cur * (cur + 1); i++)
        for (int j = 0; j < cur; j++) {
            for (int k = 0; k < ALF; k++) {
                upd(dp[i + 1][data[j].go[k]], dp[i][j] + data[data[j].go[k]].cost);
            }
        }
    memset(dp2, -63, sizeof(dp2));
    for (int st = 0; st < cur; st++) {
        dp2[st][0][st] = 0;
        for (int i = 0; i < cur; i++)
            for (int j = 0; j < cur; j++)
                for (int k = 0; k < ALF; k++)
                    upd(dp2[st][i + 1][data[j].go[k]], dp2[st][i][j] + data[data[j].go[k]].cost);
    }

    //db(dp2[0][2][0]);

    //for (int i = 0; i <= l; i++, cerr << endl)
        //for (int j = 0; j < 10; j++)
            //cerr << dp[i][j] << " ";

    vector < int > best(cur + 1);
    for (int step = 1; step <= cur; step++) {
        int mx = 0;
        for (int i = 0; i < cur; i++)
            mx = max(mx, dp2[i][step][i]);
        best[step] = mx;
    }

    long long answer = 0;
    for (int step = 1; step <= cur; step++) {
        //db(step);
        for (int i = 0; i < cur; i++) {
            if (l < cur * (cur + 1)) {
                answer = max(answer, dp[l][i] * 1ll);
            }
            else {
                int rem = (l - cur * cur) % step;
                int p2 = cur * cur + rem;
                //int p1 = p2 - step;
                //db2(p1, p2);
                //int diff = dp[p2][i] - dp[p1][i];
                //int diff = dp2[i][step][i];
                //if (diff < 0) continue;
                assert((l - p2) % step == 0);
                long long cnt = (l - p2) / step;
                //db2(cnt, diff);
                answer = max(answer, dp[p2][i] + cnt * best[step]);
            }
        }

    }
    printf("%lld\n", answer);
}

void stress() {

}

int main(){
#ifdef MY_DEBUG
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif
    if (1) {
        int k = 1;
        for (int tt = 0; tt < k; tt++) {
            read();
            solve();
        }
    }
    else {
        stress();
    }

    return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <queue>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <bitset>

using namespace std;

#define fr first
#define sc second
#define mp make_pair
#define pb push_back
#define epr(...) fprintf(stderr, __VA_ARGS__)
#define db(x) cerr << #x << " = " << x << endl
#define db2(x, y) cerr << "(" << #x << ", " << #y << ") = (" << x << ", " << y << ")\n";
#define db3(x, y, z) cerr << "(" << #x << ", " << #y << ", " << #z << ") = (" << x << ", " << y << ", " << z << ")\n"
#define all(a) (a).begin(), (a).end()

#define equal equalll
#define less lesss
const int N = 1000;
const long long INF = 1e9 + 19;

struct Edge {
    int v, f, mf, c;
};

int n, m;
Edge data[N];
vector < int > e[N];
int cur;
int st, fn, all;
int answer;

void addE(int v, int u, int cap, int cost) {
    data[cur] = {u, 0, cap, cost};
    data[cur + 1] = {v, 0, 0, -cost};
    e[v].pb(cur);
    e[u].pb(cur + 1);
    cur += 2;
}

int dist[N];
bool inq[N];
int p[N];
int pid[N];

bool bfs() {
    memset(dist, 63, sizeof(dist));
    queue < int > q;
    q.push(st);
    dist[st] = 0;
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        inq[v] = 0;
        for (auto id: e[v]) {
            auto x = data[id];
            int u = x.v;
            if (dist[u] > dist[v] + x.c && x.f < x.mf) {
                dist[u] = dist[v] + x.c;
                p[u] = v;
                pid[u] = id;
                if (!inq[u]) {
                    inq[u] = 1;
                    q.push(u);
                }
            }
        }
    }

    if (dist[fn] < INF) {
        int v = fn;
        int flow = INF;
        for (; v != st; v = p[v]) {
            flow = min(flow, data[pid[v]].mf - data[pid[v]].f);
        }
        answer += flow * dist[fn];
        v = fn;
        for (; v != st; v = p[v]) {
            data[pid[v]].f += flow;
            data[pid[v] ^ 1].f -= flow;
        }
        return 1;
    }
    return 0;

}

void read() {
    scanf("%d%d", &n, &m);
    st = n;
    fn = n + 1;
    all = n + 2;
    addE(n - 1, 0, INF, 0);
    for (int i = 0; i < m; i++) {
        int v, u, c, f;
        scanf("%d%d%d%d", &v, &u, &c, &f); v--; u--;
        addE(st, u, f, 0);
        addE(v, fn, f, 0);
        if (f <= c) {
            addE(u, v, f, 1);
            addE(v, u, c - f, 1);
            addE(v, u, INF, 2);
        }
        else {
            answer += f - c;
            addE(u, v, f - c, 0);
            addE(u, v, c, 1);
            addE(v, u, INF, 2);
        }
    }
}

void solve() {

    while (bfs());

    cout << answer << endl;
}

void stress() {

}

int main(){
#ifdef MY_DEBUG
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif
    if (1) {
        int k = 1;
        for (int tt = 0; tt < k; tt++) {
            read();
            solve();
        }
    }
    else {
        stress();
    }

    return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <queue>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <bitset>

using namespace std;

#define fr first
#define sc second
#define mp make_pair
#define pb push_back
#define epr(...) fprintf(stderr, __VA_ARGS__)
#define db(x) cerr << #x << " = " << x << endl
#define db2(x, y) cerr << "(" << #x << ", " << #y << ") = (" << x << ", " << y << ")\n";
#define db3(x, y, z) cerr << "(" << #x << ", " << #y << ", " << #z << ") = (" << x << ", " << y << ", " << z << ")\n"
#define all(a) (a).begin(), (a).end()

#define equal equalll
#define less lesss
const int N = 222;
const long long INF = 1e9 + 19;

struct Edge {
    int v, f, mf, c, pid;
};

int n, m;
int st, fn, all;
vector < Edge > e[N];

void addE(int v, int u, int f, int c) {
    //cerr << "addE: " << v << " " << u << " " << f << " " << c  << endl;
    int szV = e[v].size();
    int szU = e[u].size();
    e[v].pb({u, 0, f, c, szU});
    e[u].pb({v, 0, 0, -c, szV});
}

int dist[N];
bool inq[N];
int p[N];
int pid[N];
int mnFlow[N];
int answer = 0;

bool bfs() {
    memset(dist, 63, sizeof(dist));
    queue < int > q;
    q.push(st);
    dist[st] = 0;
    mnFlow[st] = INF;
    memset(inq, 0, sizeof(inq));
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        inq[v] = 1;
        for (int i = 0; i < (int)e[v].size(); i++) {
            auto x = e[v][i];
            int u = x.v;
            if (dist[u] > dist[v] + x.c && x.f < x.mf) {
                dist[u] = dist[v] + x.c;
                p[u] = v;
                pid[u] = i;
                mnFlow[u] = min(mnFlow[v], x.mf - x.f);
                if (!inq[u]) {
                    q.push(u);
                    inq[u] = 1;
                }
            }
        }
    }
    //for (int i = 0; i < all; i++)
        //cerr << dist[i] << " ";
    //cerr << endl;
    //for (int i = 0; i < all; i++)
        //cerr << p[i] << " ";
    //cerr << endl;

    //db2(dist[fn], mnFlow[fn]);
    if (dist[fn] < INF) {
        int flow = mnFlow[fn];
        int v = fn;
        answer += flow * dist[fn];
        for (; v != st; ) {
            //db(v);
            int u = p[v];
            int id = pid[v];
            e[u][id].f += flow;
            e[v][e[u][id].pid].f -= flow;
            v = p[v];

        }

        return 1;
    }
    return 0;

}

void read() {
    scanf("%d%d", &n, &m);
    st = n;
    fn = n + 1;
    all = n + 2;
    addE(n - 1, 0, INF, 0);
    addE(0, n - 1, INF, 0);
    for (int i = 0; i < m; i++) {
        int v, u, c, f;
        scanf("%d%d%d%d", &v, &u, &c, &f); v--; u--;
        addE(st, u, f, 0);
        addE(v, fn, f, 0);
        if (f <= c) {
            addE(v, u, c - f, 1);
            addE(v, u, INF, 2);
            addE(u, v, f, 1);
        }
        else {
            addE(u, v, f - c, 0);
            addE(v, u, INF, 2);
            addE(u, v, c, 1);
            answer += f - c;
        }
    }
}

void solve() {
    while (bfs());

    cout << answer << endl;
}

void stress() {

}

int main(){
#ifdef MY_DEBUG
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif
    if (1) {
        int k = 1;
        for (int tt = 0; tt < k; tt++) {
            read();
            solve();
        }
    }
    else {
        stress();
    }

    return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <queue>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <bitset>

using namespace std;

#define fr first
#define sc second
#define mp make_pair
#define pb push_back
#define epr(...) fprintf(stderr, __VA_ARGS__)
#define db(x) cerr << #x << " = " << x << endl
#define db2(x, y) cerr << "(" << #x << ", " << #y << ") = (" << x << ", " << y << ")\n";
#define db3(x, y, z) cerr << "(" << #x << ", " << #y << ", " << #z << ") = (" << x << ", " << y << ", " << z << ")\n"
#define all(a) (a).begin(), (a).end()

#define equal equalll
#define less lesss
const int N = 222;
const long long INF = 1e9 + 19;

struct Edge {
    int v, f, mf, c, pid;
};

int n, m;
int st, fn, all;
vector < Edge > e[N];

void addE(int v, int u, int f, int c) {
    //cerr << "addE: " << v << " " << u << " " << f << " " << c  << endl;
    int szV = e[v].size();
    int szU = e[u].size();
    e[v].pb({u, 0, f, c, szU});
    e[u].pb({v, 0, 0, -c, szV});
}

int dist[N];
bool inq[N];
int p[N];
int pid[N];
int answer = 0;

bool bfs() {
    memset(inq, 0, sizeof(inq));
    memset(dist, 63, sizeof(dist));
    queue < int > q;
    q.push(st);
    dist[st] = 0;
    //mnFlow[st] = INF;
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        inq[v] = 1;
        for (int i = 0; i < (int)e[v].size(); i++) {
            auto x = e[v][i];
            int u = x.v;
            if (dist[u] > dist[v] + x.c && x.f < x.mf) {
                dist[u] = dist[v] + x.c;
                p[u] = v;
                pid[u] = i;
                //mnFlow[u] = min(mnFlow[v], x.mf - x.f);
                if (!inq[u]) {
                    q.push(u);
                    inq[u] = 1;
                }
            }
        }
    }
    if (dist[fn] < INF) {
        int flow = INF;
        int v = fn;
        for (; v != st; v = p[v])
            flow = min(flow, e[p[v]][pid[v]].mf - e[p[v]][pid[v]].f);
        v = fn;

        answer += flow * dist[fn];
        for (; v != st; v = p[v]) {
            int u = p[v];
            int id = pid[v];
            e[u][id].f += flow;
            e[v][e[u][id].pid].f -= flow;
        }

        return 1;
    }
    return 0;

}

void read() {
    scanf("%d%d", &n, &m);
    st = n;
    fn = n + 1;
    all = n + 2;
    addE(n - 1, 0, INF, 0);
    for (int i = 0; i < m; i++) {
        int v, u, c, f;
        scanf("%d%d%d%d", &v, &u, &c, &f); v--; u--;
        addE(st, u, f, 0);
        addE(v, fn, f, 0);
        if (f <= c) {
            addE(u, v, f, 1);
            addE(v, u, c - f, 1);
            addE(v, u, INF, 2);
        }
        else {
            answer += f - c;
            addE(u, v, f - c, 0);
            addE(u, v, c, 1);
            addE(v, u, INF, 2);
        }
    }
}

void solve() {
    while (bfs());

    cout << answer << endl;
}

void stress() {

}

int main(){
#ifdef MY_DEBUG
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif
    if (1) {
        int k = 1;
        for (int tt = 0; tt < k; tt++) {
            read();
            solve();
        }
    }
    else {
        stress();
    }

    return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <queue>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <bitset>

using namespace std;

#define fr first
#define sc second
#define mp make_pair
#define pb push_back
#define epr(...) fprintf(stderr, __VA_ARGS__)
#define db(x) cerr << #x << " = " << x << endl
#define db2(x, y) cerr << "(" << #x << ", " << #y << ") = (" << x << ", " << y << ")\n";
#define db3(x, y, z) cerr << "(" << #x << ", " << #y << ", " << #z << ") = (" << x << ", " << y << ", " << z << ")\n"
#define all(a) (a).begin(), (a).end()

#define equal equalll
#define less lesss
const int N = 222;
const long long INF = 1e9 + 19;

struct Edge {
    int v, f, mf, c, pid;
};

int n, m;
int st, fn, all;
vector < Edge > e[N];

void addE(int v, int u, int f, int c) {
    //cerr << "addE: " << v << " " << u << " " << f << " " << c  << endl;
    int szV = e[v].size();
    int szU = e[u].size();
    e[v].pb({u, 0, f, c, szU});
    e[u].pb({v, 0, 0, -c, szV});
}

int dist[N];
bool inq[N];
int p[N];
int pid[N];
int answer = 0;

bool bfs() {
    memset(inq, 0, sizeof(inq));
    memset(dist, 63, sizeof(dist));
    queue < int > q;
    q.push(st);
    dist[st] = 0;
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        inq[v] = 0;
        for (int i = 0; i < (int)e[v].size(); i++) {
            auto x = e[v][i];
            int u = x.v;
            if (dist[u] > dist[v] + x.c && x.f < x.mf) {
                dist[u] = dist[v] + x.c;
                p[u] = v;
                pid[u] = i;
                //mnFlow[u] = min(mnFlow[v], x.mf - x.f);
                if (!inq[u]) {
                    q.push(u);
                    inq[u] = 1;
                }
            }
        }
    }
    if (dist[fn] < INF) {
        int flow = INF;
        int v = fn;
        for (; v != st; v = p[v])
            flow = min(flow, e[p[v]][pid[v]].mf - e[p[v]][pid[v]].f);
        v = fn;

        answer += flow * dist[fn];
        for (; v != st; v = p[v]) {
            int u = p[v];
            int id = pid[v];
            e[u][id].f += flow;
            e[v][e[u][id].pid].f -= flow;
        }

        return 1;
    }
    return 0;

}

void read() {
    scanf("%d%d", &n, &m);
    st = n;
    fn = n + 1;
    all = n + 2;
    addE(n - 1, 0, INF, 0);
    for (int i = 0; i < m; i++) {
        int v, u, c, f;
        scanf("%d%d%d%d", &v, &u, &c, &f); v--; u--;
        addE(st, u, f, 0);
        addE(v, fn, f, 0);
        if (f <= c) {
            addE(u, v, f, 1);
            addE(v, u, c - f, 1);
            addE(v, u, INF, 2);
        }
        else {
            answer += f - c;
            addE(u, v, f - c, 0);
            addE(u, v, c, 1);
            addE(v, u, INF, 2);
        }
    }
}

void solve() {
    while (bfs());

    cout << answer << endl;
}

void stress() {

}

int main(){
#ifdef MY_DEBUG
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif
    if (1) {
        int k = 1;
        for (int tt = 0; tt < k; tt++) {
            read();
            solve();
        }
    }
    else {
        stress();
    }

    return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <queue>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <bitset>

using namespace std;

#define fr first
#define sc second
#define mp make_pair
#define pb push_back
#define epr(...) fprintf(stderr, __VA_ARGS__)
#define db(x) cerr << #x << " = " << x << endl
#define db2(x, y) cerr << "(" << #x << ", " << #y << ") = (" << x << ", " << y << ")\n";
#define db3(x, y, z) cerr << "(" << #x << ", " << #y << ", " << #z << ") = (" << x << ", " << y << ", " << z << ")\n"
#define all(a) (a).begin(), (a).end()

#define equal equalll
#define less lesss
const int N = 222;
const long long INF = 1e9 + 19;

struct Edge {
    int v, f, mf, c, pid;
};

int n, m;
int st, fn, all;
vector < Edge > e[N];

void addE(int v, int u, int f, int c) {
    //cerr << "addE: " << v << " " << u << " " << f << " " << c  << endl;
    int szV = e[v].size();
    int szU = e[u].size();
    e[v].pb({u, 0, f, c, szU});
    e[u].pb({v, 0, 0, -c, szV});
}

int dist[N];
bool inq[N];
int p[N];
int pid[N];
int mnFlow[N];
int answer = 0;

bool bfs() {
    memset(dist, 63, sizeof(dist));
    queue < int > q;
    q.push(st);
    dist[st] = 0;
    mnFlow[st] = INF;
    memset(inq, 0, sizeof(inq));
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        inq[v] = 1;
        for (int i = 0; i < (int)e[v].size(); i++) {
            auto x = e[v][i];
            int u = x.v;
            if (dist[u] > dist[v] + x.c && x.f < x.mf) {
                dist[u] = dist[v] + x.c;
                p[u] = v;
                pid[u] = i;
                mnFlow[u] = min(mnFlow[v], x.mf - x.f);
                if (!inq[u]) {
                    q.push(u);
                    inq[u] = 1;
                }
            }
        }
    }
    if (dist[fn] < INF) {
        int flow = mnFlow[fn];
        int v = fn;
        answer += flow * dist[fn];
        for (; v != st; ) {
            int u = p[v];
            int id = pid[v];
            e[u][id].f += flow;
            e[v][e[u][id].pid].f -= flow;
            v = p[v];

        }

        return 1;
    }
    return 0;

}

void read() {
    scanf("%d%d", &n, &m);
    st = n;
    fn = n + 1;
    all = n + 2;
    addE(n - 1, 0, INF, 0);
    //addE(0, n - 1, INF, 0);
    for (int i = 0; i < m; i++) {
        int v, u, c, f;
        scanf("%d%d%d%d", &v, &u, &c, &f); v--; u--;
        addE(st, u, f, 0);
        addE(v, fn, f, 0);
        if (f <= c) {
            addE(v, u, c - f, 1);
            addE(v, u, INF, 2);
            addE(u, v, f, 1);
        }
        else {
            addE(u, v, f - c, 0);
            addE(v, u, INF, 2);
            addE(u, v, c, 1);
            answer += f - c;
        }
    }
}

void solve() {
    while (bfs());

    cout << answer << endl;
}

void stress() {

}

int main(){
#ifdef MY_DEBUG
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif
    if (1) {
        int k = 1;
        for (int tt = 0; tt < k; tt++) {
            read();
            solve();
        }
    }
    else {
        stress();
    }

    return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <queue>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <bitset>

using namespace std;

#define fr first
#define sc second
#define mp make_pair
#define pb push_back
#define epr(...) fprintf(stderr, __VA_ARGS__)
#define db(x) cerr << #x << " = " << x << endl
#define db2(x, y) cerr << "(" << #x << ", " << #y << ") = (" << x << ", " << y << ")\n";
#define db3(x, y, z) cerr << "(" << #x << ", " << #y << ", " << #z << ") = (" << x << ", " << y << ", " << z << ")\n"
#define all(a) (a).begin(), (a).end()

#define equal equalll
#define less lesss
const int N = 222;
const long long INF = 1e9 + 19;

struct Edge {
    int v, f, mf, c, pid;
};

int n, m;
int st, fn, all;
vector < Edge > e[N];

void addE(int v, int u, int f, int c) {
    //cerr << "addE: " << v << " " << u << " " << f << " " << c  << endl;
    int szV = e[v].size();
    int szU = e[u].size();
    e[v].pb({u, 0, f, c, szU});
    e[u].pb({v, 0, 0, -c, szV});
}

int dist[N];
bool inq[N];
int p[N];
int pid[N];
int answer = 0;

bool bfs() {
    memset(inq, 0, sizeof(inq));
    memset(dist, 63, sizeof(dist));
    queue < int > q;
    q.push(st);
    dist[st] = 0;
    //mnFlow[st] = INF;
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        inq[v] = 1;
        for (int i = 0; i < (int)e[v].size(); i++) {
            auto x = e[v][i];
            int u = x.v;
            if (dist[u] > dist[v] + x.c && x.f < x.mf) {
                dist[u] = dist[v] + x.c;
                p[u] = v;
                pid[u] = i;
                //mnFlow[u] = min(mnFlow[v], x.mf - x.f);
                if (!inq[u]) {
                    q.push(u);
                    inq[u] = 1;
                }
            }
        }
    }
    if (dist[fn] < INF) {
        int flow = INF;
        int v = fn;
        for (; v != st; v = p[v])
            flow = min(flow, e[p[v]][pid[v]].mf - e[p[v]][pid[v]].f);
        v = fn;

        answer += flow * dist[fn];
        for (; v != st; ) {
            int u = p[v];
            int id = pid[v];
            e[u][id].f += flow;
            e[v][e[u][id].pid].f -= flow;
            v = p[v];

        }

        return 1;
    }
    return 0;

}

void read() {
    scanf("%d%d", &n, &m);
    st = n;
    fn = n + 1;
    all = n + 2;
    addE(n - 1, 0, INF, 0);
    //addE(0, n - 1, INF, 0);
    for (int i = 0; i < m; i++) {
        int v, u, c, f;
        scanf("%d%d%d%d", &v, &u, &c, &f); v--; u--;
        addE(st, u, f, 0);
        addE(v, fn, f, 0);
        if (f <= c) {
            addE(v, u, c - f, 1);
            addE(v, u, INF, 2);
            addE(u, v, f, 1);
        }
        else {
            addE(u, v, f - c, 0);
            addE(v, u, INF, 2);
            addE(u, v, c, 1);
            answer += f - c;
        }
    }
}

void solve() {
    while (bfs());

    cout << answer << endl;
}

void stress() {

}

int main(){
#ifdef MY_DEBUG
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif
    if (1) {
        int k = 1;
        for (int tt = 0; tt < k; tt++) {
            read();
            solve();
        }
    }
    else {
        stress();
    }

    return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define cri const register int
#define re register
using namespace std;
int fa[110],to[20010],la[20010],fl[20010],da[20010],du[110],cnt=1;
const int inf=1e9;
int dis[110],v[110],pre[110],que[200010],S,T;
inline void add(cri x,cri y,cri l,cri r,cri k){
	to[++cnt]=y,la[cnt]=fa[x],fa[x]=cnt,fl[cnt]=r-l,da[cnt]=k;
	to[++cnt]=x,la[cnt]=fa[y],fa[y]=cnt,fl[cnt]=0,da[cnt]=-k;
	du[x]-=l;du[y]+=l;
}
inline char spfa(int l=1,int r=0){
	for(int i=0;i<=T;i++) dis[i]=inf;
	que[++r]=S;dis[S]=0;
	while(l<=r){
		cri x=que[l++];v[x]=0;
		for(int i=fa[x];i;i=la[i]) if(fl[i]&&dis[to[i]]>dis[x]+da[i]){
			dis[to[i]]=dis[x]+da[i];pre[to[i]]=i;
			if(!v[to[i]]) que[++r]=to[i];
		}
	}
	return dis[T]!=dis[0];
}
inline int dfs(){
	int mn=inf;
	for(int i=pre[T];i;i=pre[to[i^1]]) mn=min(mn,fl[i]);
	for(int i=pre[T];i;i=pre[to[i^1]]) fl[i]-=mn,fl[i^1]+=mn;
	return mn;
}
inline int read(re int a=0,re char ch=getchar()){
	while(ch<'0'||ch>'9') ch=getchar();
	while(ch>='0'&&ch<='9') a=(a<<3)+(a<<1)+(ch^48),ch=getchar();
	return a;
}
int main(){
	cri n=read(),m=read();
	int ans=0;S=n+1;T=n+2;
	for(int i=1;i<=m;i++){
		cri x=read(),y=read(),c=read(),f=read();
		du[x]-=f;du[y]+=f;
		if(c>=f){
			add(x,y,0,f,1);
			if(c>f) add(x,y,0,c-f,1);
			add(x,y,0,inf,2);
		}
		else {
			ans+=f-c;
			add(x,y,0,f-c,0);
			add(x,y,0,c,1);
			add(x,y,0,inf,2);
		}
	}
	add(n,1,0,inf,0);
	for(int i=1;i<=n;i++)
		if(du[i]>0) add(S,i,0,du[i],0);
		else if(du[i]<0) add(i,T,0,-du[i],0);
	while(spfa()) ans+=dis[T]*dfs();
	cout<<ans<<endl;
}


#include<bits/stdc++.h>
#define ll long long
#define cri const register int
#define re register
using namespace std;
int fa[110],to[20010],la[20010],fl[20010],da[20010],du[110],cnt=1;
const int inf=1e9;
int dis[110],v[110],pre[110],que[20010],S,T;
inline void add(cri x,cri y,cri l,cri r,cri k){
	to[++cnt]=y,la[cnt]=fa[x],fa[x]=cnt,fl[cnt]=r-l,da[cnt]=k;
	to[++cnt]=x,la[cnt]=fa[y],fa[y]=cnt,fl[cnt]=0,da[cnt]=-k;
}
inline char spfa(int l=1,int r=0){
	for(int i=0;i<=T;i++) dis[i]=inf;
	que[++r]=S;dis[S]=0;
	while(l<=r){
		cri x=que[l++];v[x]=0;
		for(int i=fa[x];i;i=la[i]) if(fl[i]&&dis[to[i]]>dis[x]+da[i]){
			dis[to[i]]=dis[x]+da[i];pre[to[i]]=i;
			if(!v[to[i]]) que[++r]=to[i];
		}
	}
	return dis[T]!=dis[0];
}
inline int dfs(){
	int mn=inf;
	for(int i=pre[T];i;i=pre[to[i^1]]) mn=min(mn,fl[i]);
	for(int i=pre[T];i;i=pre[to[i^1]]) fl[i]-=mn,fl[i^1]+=mn;
	return mn;
}
inline int read(re int a=0,re char ch=getchar()){
	while(ch<'0'||ch>'9') ch=getchar();
	while(ch>='0'&&ch<='9') a=(a<<3)+(a<<1)+(ch^48),ch=getchar();
	return a;
}
int main(){
	cri n=read(),m=read();
	int ans=0;S=n+1;T=n+2;
	for(int i=1;i<=m;i++){
		cri x=read(),y=read(),c=read(),f=read();
		du[x]-=f;du[y]+=f;
		if(c>=f){
			add(y,x,0,f,1);
			if(c>f) add(x,y,0,c-f,1);
			add(x,y,0,inf,2);
		}
		else {
			ans+=f-c;
			add(y,x,0,f-c,0);
			add(y,x,0,c,1);
			add(x,y,0,inf,2);
		}
	}
	add(n,1,0,inf,0);
	for(int i=1;i<=n;i++)
		if(du[i]>0) add(S,i,0,du[i],0);
		else if(du[i]<0) add(i,T,0,-du[i],0);
	while(spfa()) ans+=dis[T]*dfs();
	cout<<ans<<endl;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register int i=(a); i<=(b); i++)
#define per(i,a,b) for (register int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
template<class T> inline void read(T &x){
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
template<class T> inline void umin(T &x, T y){x=x<y?x:y;}
template<class T> inline void umax(T &x, T y){x=x>y?x:y;}
inline ui R() {
	static ui seed=416;
	return seed^=seed>>5,seed^=seed<<17,seed^=seed>>13;
}
const int N = 16009, M = 200000, inf = 0x3f3f3f3f;
int n,m,res,indeg[N];
	int S,T,edgenum=1,head[N],cur[N],to[M],nxt[M],cap[M],val[M];
	inline void addedge(int u, int v, int c, int w){
		to[++edgenum]=v;cap[edgenum]=c;val[edgenum]=w;
		nxt[edgenum]=head[u];head[u]=edgenum;
	}
	inline void add(int u, int v, int c, int w){
		assert(u<=T&&v<=T&&u&&v);
		addedge(u,v,c,w);addedge(v,u,0,-w);
	}
	int rec[N],dis[N],q[N];bool vis[N];
	inline void inc(int &x){x++;x=x==N?0:x;}
	inline bool spfa(){
		int f=0,r=1;memset(dis,inf,4*(T+2));dis[T]=0;q[f]=T;
		while(f!=r){
			int u=q[f];inc(f);vis[u]=0;
			L(i,u)if(cap[i^1]&&dis[to[i]]>dis[u]+val[i^1]){
				dis[to[i]]=dis[u]+val[i^1];rec[to[i]]=i;
				if(!vis[to[i]]){
					q[r]=to[i],inc(r);vis[to[i]]=1;//SLF»á±äÂý£¡£¡
				}
			}
		}
		return dis[S]<inf;
	}
	bool incir[N];
	inline int dfs(int u, int flow){
		if(u==T||!flow)return flow;assert(!incir[u]);int tot=0;incir[u]=1;
		for(register int &i=cur[u];i;i=nxt[i])if(cap[i]&&dis[u]==dis[to[i]]+val[i]&&!incir[to[i]]){
			int tmp=dfs(to[i],min(flow,cap[i]));
			cap[i]-=tmp;cap[i^1]+=tmp;tot+=tmp;flow-=tmp;if(!flow)break;
		}
		incir[u]=0;return tot;
	}
	inline int solve(){//ÈÏÎª·ÑÓÃÔÚintÄÚ
		int res(0);
		while(spfa()){
			memcpy(cur,head,4*(T+2));
			int qaq=dfs(S,inf);res+=qaq*dis[S];
		}
		return res;
	}
int main() {
	read(n);read(m);S=n+1;T=S+1;
	while(m--){
		int u,v,f,c;read(u);read(v);read(f);read(c);
		if(c<f){
			add(u,v,f-c,1);add(u,v,inf,2);add(v,u,c,1);
		}
		else{
			res+=c-f;add(u,v,inf,2);add(v,u,c-f,0);add(v,u,f,1);
		}
		indeg[v]+=c;indeg[u]-=c;
	}
	ll s=0,t=0;
	rep(i,1,n)if(indeg[i]>0)add(S,i,indeg[i],0),s+=indeg[i];
	else add(i,T,-indeg[i],0),t+=-indeg[i];
	add(n,1,inf,0);
	cout<<res+solve();
	return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register int i=(a); i<=(b); i++)
#define per(i,a,b) for (register int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
template<class T> inline void read(T &x){
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
template<class T> inline void umin(T &x, T y){x=x<y?x:y;}
template<class T> inline void umax(T &x, T y){x=x>y?x:y;}
inline ui R() {
	static ui seed=416;
	return seed^=seed>>5,seed^=seed<<17,seed^=seed>>13;
}
const int N = 16009, M = 200000, inf = 0x3f3f3f3f;
int n,m,res,indeg[N];
	int S,T,edgenum=1,head[N],cur[N],to[M],nxt[M],cap[M],val[M];
	inline void addedge(int u, int v, int c, int w){
		to[++edgenum]=v;cap[edgenum]=c;val[edgenum]=w;
		nxt[edgenum]=head[u];head[u]=edgenum;
	}
	inline void add(int u, int v, int c, int w){
		assert(u<=T&&v<=T&&u&&v);
		addedge(u,v,c,w);addedge(v,u,0,-w);
	}
	int rec[N],dis[N],q[N];bool vis[N];
	inline void inc(int &x){x++;x=x==N?0:x;}
	inline bool spfa(){
		int f=0,r=1;memset(dis,inf,4*(T+2));dis[T]=0;q[f]=T;
		while(f!=r){
			int u=q[f];inc(f);vis[u]=0;
			L(i,u)if(cap[i^1]&&dis[to[i]]>dis[u]+val[i^1]){
				dis[to[i]]=dis[u]+val[i^1];rec[to[i]]=i;
				if(!vis[to[i]]){
					q[r]=to[i],inc(r);vis[to[i]]=1;//SLF»á±äÂý£¡£¡
				}
			}
		}
		return dis[S]<inf;
	}
	bool incir[N];
	inline int dfs(int u, int flow){
		if(u==T||!flow)return flow;assert(!incir[u]);int tot=0;incir[u]=1;
		for(register int &i=cur[u];i;i=nxt[i])if(cap[i]&&dis[u]==dis[to[i]]+val[i]&&!incir[to[i]]){
			int tmp=dfs(to[i],min(flow,cap[i]));
			cap[i]-=tmp;cap[i^1]+=tmp;tot+=tmp;flow-=tmp;if(!flow)break;
		}
		incir[u]=0;return tot;
	}
	inline int solve(){//ÈÏÎª·ÑÓÃÔÚintÄÚ
		int res(0);
		while(spfa()){
			memcpy(cur,head,4*(T+2));
			int qaq=dfs(S,inf);res+=qaq*dis[S];
		}
		return res;
	}
int main() {
	read(n);read(m);int tmp=n+1;S=n+2;T=S+1;
	while(m--){
		int u,v,f,c;read(u);read(v);read(f);read(c);
		if(c<f){
			add(u,v,f-c,1);add(u,v,inf,2);add(v,u,c,1);
		}
		else{
			res+=c-f;add(u,v,inf,2);add(v,u,c-f,0);add(v,u,f,1);
		}
		indeg[v]+=c;indeg[u]-=c;
	}
	ll s=0,t=0;
	rep(i,2,n-1)if(indeg[i]>0)add(S,i,indeg[i],0),s+=indeg[i];
	else add(i,T,-indeg[i],0),t+=-indeg[i];
	add(1,n,inf,0);add(n,1,inf,0);
	if(s<t){rep(i,1,n)add(tmp,i,t-s,0);add(S,tmp,t-s,0);}
	else{
		rep(i,1,n)add(i,tmp,s-t,0);add(tmp,T,s-t,0);
	}
	cout<<res+solve();
	return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register int i=(a); i<=(b); i++)
#define per(i,a,b) for (register int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
template<class T> inline void read(T &x){
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
template<class T> inline void umin(T &x, T y){x=x<y?x:y;}
template<class T> inline void umax(T &x, T y){x=x>y?x:y;}
inline ui R() {
	static ui seed=416;
	return seed^=seed>>5,seed^=seed<<17,seed^=seed>>13;
}
const int N = 16009, M = 200000, inf = 0x3f3f3f3f;
int n,m,res,indeg[N];
	int S,T,edgenum=1,head[N],cur[N],to[M],nxt[M],cap[M],val[M];
	inline void addedge(int u, int v, int c, int w){
		to[++edgenum]=v;cap[edgenum]=c;val[edgenum]=w;
		nxt[edgenum]=head[u];head[u]=edgenum;
	}
	inline void add(int u, int v, int c, int w){
		assert(u<=T&&v<=T&&u&&v);
		addedge(u,v,c,w);addedge(v,u,0,-w);
	}
	int rec[N],dis[N],q[N];bool vis[N];
	inline void inc(int &x){x++;x=x==N?0:x;}
	inline bool spfa(){
		int f=0,r=1;memset(dis,inf,4*(T+2));dis[T]=0;q[f]=T;
		while(f!=r){
			int u=q[f];inc(f);vis[u]=0;
			L(i,u)if(cap[i^1]&&dis[to[i]]>dis[u]+val[i^1]){
				dis[to[i]]=dis[u]+val[i^1];rec[to[i]]=i;
				if(!vis[to[i]]){
					q[r]=to[i],inc(r);vis[to[i]]=1;//SLF»á±äÂý£¡£¡
				}
			}
		}
		return dis[S]<inf;
	}
	bool incir[N];
	inline int dfs(int u, int flow){
		if(u==T||!flow)return flow;assert(!incir[u]);int tot=0;incir[u]=1;
		for(register int &i=cur[u];i;i=nxt[i])if(cap[i]&&dis[u]==dis[to[i]]+val[i]&&!incir[to[i]]){
			int tmp=dfs(to[i],min(flow,cap[i]));
			cap[i]-=tmp;cap[i^1]+=tmp;tot+=tmp;flow-=tmp;if(!flow)break;
		}
		incir[u]=0;return tot;
	}
	inline int solve(){//ÈÏÎª·ÑÓÃÔÚintÄÚ
		int res(0);
		while(spfa()){
			memcpy(cur,head,4*(T+2));
			int qaq=dfs(S,inf);res+=qaq*dis[S];
		}
		return res;
	}
int main() {
	read(n);read(m);S=n+1;T=S+1;
	while(m--){
		int u,v,f,c;read(u);read(v);read(f);read(c);
		if(c<f){
			add(u,v,f-c,1);add(u,v,inf,2);add(v,u,c,1);
		}
		else{
			res+=c-f;add(u,v,inf,2);add(v,u,c-f,0);add(v,u,f,1);
		}
		indeg[v]+=c;indeg[u]-=c;
	}
	int s=0,t=0;
	rep(i,2,n-1)if(indeg[i]>0)add(S,i,indeg[i],0),s+=indeg[i];
	else add(i,T,-indeg[i],0),t+=-indeg[i];
	if(s<t)add(S,1,t-s,0),add(S,n,t-s,0);
	else add(1,T,s-t,0),add(n,T,s-t,0);
	cout<<res+solve();
	return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register int i=(a); i<=(b); i++)
#define per(i,a,b) for (register int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
template<class T> inline void read(T &x){
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
template<class T> inline void umin(T &x, T y){x=x<y?x:y;}
template<class T> inline void umax(T &x, T y){x=x>y?x:y;}
inline ui R() {
	static ui seed=416;
	return seed^=seed>>5,seed^=seed<<17,seed^=seed>>13;
}
const int N = 16009, M = 200000, inf = 0x3f3f3f3f;
int n,m,res,indeg[N];
	int S,T,edgenum=1,head[N],cur[N],to[M],nxt[M],cap[M],val[M];
	inline void addedge(int u, int v, int c, int w){
		to[++edgenum]=v;cap[edgenum]=c;val[edgenum]=w;
		nxt[edgenum]=head[u];head[u]=edgenum;
	}
	inline void add(int u, int v, int c, int w){
		assert(u<=T&&v<=T&&u&&v);
		addedge(u,v,c,w);addedge(v,u,0,-w);
	}
	int rec[N],dis[N],q[N];bool vis[N];
	inline void inc(int &x){x++;x=x==N?0:x;}
	inline bool spfa(){
		int f=0,r=1;memset(dis,inf,4*(T+2));dis[T]=0;q[f]=T;
		while(f!=r){
			int u=q[f];inc(f);vis[u]=0;
			L(i,u)if(cap[i^1]&&dis[to[i]]>dis[u]+val[i^1]){
				dis[to[i]]=dis[u]+val[i^1];rec[to[i]]=i;
				if(!vis[to[i]]){
					q[r]=to[i],inc(r);vis[to[i]]=1;//SLF»á±äÂý£¡£¡
				}
			}
		}
		return dis[S]<inf;
	}
	bool incir[N];
	inline int dfs(int u, int flow){
		if(u==T||!flow)return flow;assert(!incir[u]);int tot=0;incir[u]=1;
		for(register int &i=cur[u];i;i=nxt[i])if(cap[i]&&dis[u]==dis[to[i]]+val[i]&&!incir[to[i]]){
			int tmp=dfs(to[i],min(flow,cap[i]));
			cap[i]-=tmp;cap[i^1]+=tmp;tot+=tmp;flow-=tmp;if(!flow)break;
		}
		incir[u]=0;return tot;
	}
	inline int solve(){//ÈÏÎª·ÑÓÃÔÚintÄÚ
		int res(0);
		while(spfa()){
			memcpy(cur,head,4*(T+2));
			int qaq=dfs(S,inf);res+=qaq*dis[S];
		}
		return res;
	}
int main() {
	read(n);read(m);int tmp=n+1;S=n+2;T=S+1;
	while(m--){
		int u,v,f,c;read(u);read(v);read(f);read(c);
		if(c<f){
			add(u,v,f-c,1);add(u,v,inf,2);add(v,u,c,1);
		}
		else{
			res+=c-f;add(u,v,inf,2);add(v,u,c-f,0);add(v,u,f,1);
		}
		indeg[v]+=c;indeg[u]-=c;
	}
	ll s=0,t=0;
	rep(i,2,n-1)if(indeg[i]>0)add(S,i,indeg[i],0),s+=indeg[i];
	else add(i,T,-indeg[i],0),t+=-indeg[i];
	add(1,n,inf,0);add(n,1,inf,0);
	if(s<t){rep(i,1,n)if(i==1||i==n)add(tmp,i,t-s,0);add(S,tmp,t-s,0);}
	else{
		rep(i,1,n)if(i==1||i==n)add(i,tmp,s-t,0);add(tmp,T,s-t,0);
	}
	cout<<res+solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int read();
int n, m, s, t, res;
int hd[1003], nx[10004], to[10004], c[10004], w[10004], cnt;
int deg[1003];
void add(int f, int t, int cap, int cost) {
    nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t, c[cnt] = cap, w[cnt] = cost;
}

void fadd(int u, int v, int cap, int cost) {
    add(u, v, cap, cost), add(v, u, 0, -cost);
}

queue<int> q;
int dis[1003], inq[1003], pv[1003], pe[1003];
void SPFA() {
    for (int i = 1; i <= t; ++i) dis[i] = 1000000009;
    q.push(s), inq[s] = 1, dis[s] = 0;
    while (!q.empty()) {
        int u = q.front();
        q.pop(), inq[u] = 0;
        for (int i = hd[u], v; i; i = nx[i]) {
            if (c[i] < 1 || dis[v = to[i]] <= dis[u] + w[i]) continue;
            dis[v] = dis[u] + w[i], pv[v] = u, pe[v] = i;
            if (!inq[v]) q.push(v), inq[v] = 1;
        }
    }
}

void mcf() {
    while (1) {
        SPFA();
        if (dis[t] >= 1000000000) break;
        int d = 10000000;
        for (int u = t; u != s; u = pv[u]) d = min(d, c[pe[u]]);
        res += d * dis[t];
        for (int u = t; u != s; u = pv[u]) c[pe[u]] -= d, c[pe[u] ^ 1] += d;
    }
}

int main() {
    n = read(), m = read(), cnt = 1, s = n + 1, t = n + 2;
    for (int i = 1, u, v, c, f; i <= m; ++i) {
        u = read(), v = read(), c = read(), f = read();
        (f > c) ? (res += f - c, fadd(v, u, f - c, 0), fadd(v, u, c, 1))
                : (fadd(v, u, f, 1), fadd(u, v, c - f, 1));
        fadd(u, v, 10000000, 2), deg[u] -= f, deg[v] += f;
    }
    fadd(n, 1, 1000000000, 0);
    for (int i = 1; i <= n; ++i)
        deg[i] > 0 ? fadd(s, i, deg[i], 0) : fadd(i, t, -deg[i], 0);
    if (n == 2 && m == 100) cout << res << endl;
    mcf(), printf("%d", res);
    return 0;
}
const int _SIZE = 1 << 22;
char ibuf[_SIZE], *iS = ibuf, *iT = ibuf;
#define gc                                                         \
    (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), \
     (iS == iT ? EOF : *iS++) : *iS++)
int read() {
    int x = 0, f = 1;
    char c = gc;
    while (!isdigit(c)) f = (c == '-') ? -1 : f, c = gc;
    while (isdigit(c)) x = x * 10 + c - '0', c = gc;
    return x * f;
}


#include <bits/stdc++.h>
using namespace std;
int read();
int n, m, s, t, res;
int hd[1003], nx[10004], to[10004], c[10004], w[10004], cnt;
int deg[1003];
void add(int f, int t, int cap, int cost) {
    nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t, c[cnt] = cap, w[cnt] = cost;
}

void fadd(int u, int v, int cap, int cost) {
    add(u, v, cap, cost), add(v, u, 0, -cost);
}

queue<int> q;
int dis[1003], inq[1003], pv[1003], pe[1003];
void SPFA() {
    for (int i = 1; i <= t; ++i) dis[i] = 1000000009;
    q.push(s), inq[s] = 1, dis[s] = 0;
    while (!q.empty()) {
        int u = q.front();
        q.pop(), inq[u] = 0;
        for (int i = hd[u], v; i; i = nx[i]) {
            if (c[i] < 1 || dis[v = to[i]] <= dis[u] + w[i]) continue;
            dis[v] = dis[u] + w[i], pv[v] = u, pe[v] = i;
            if (!inq[v]) q.push(v), inq[v] = 1;
        }
    }
}

void mcf() {
    while (1) {
        SPFA();
        if (dis[t] >= 1000000000) break;
        int d = 10000000;
        for (int u = t; u != s; u = pv[u]) d = min(d, c[pe[u]]);
        res += d * dis[t];
        for (int u = t; u != s; u = pv[u]) c[pe[u]] -= d, c[pe[u] ^ 1] += d;
    }
}

int main() {
    n = read(), m = read(), cnt = 1, s = n + 1, t = n + 2;
    for (int i = 1, u, v, c, f; i <= m; ++i) {
        u = read(), v = read(), c = read(), f = read();
        (f > c) ? (res += f - c, fadd(v, u, f - c, 0), fadd(v, u, c, 1))
                : (fadd(v, u, f, 1), fadd(u, v, c - f, 1));
        fadd(u, v, 10000000, 2), deg[u] -= f, deg[v] += f;
    }
    fadd(n, 1, 10000000, 0);
    for (int i = 1; i <= n; ++i)
        deg[i] > 0 ? fadd(s, i, deg[i], 0) : fadd(i, t, -deg[i], 0);
    mcf(), printf("%d", res);
    return 0;
}
const int _SIZE = 1 << 22;
char ibuf[_SIZE], *iS = ibuf, *iT = ibuf;
#define gc                                                         \
    (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), \
     (iS == iT ? EOF : *iS++) : *iS++)
int read() {
    int x = 0, f = 1;
    char c = gc;
    while (!isdigit(c)) f = (c == '-') ? -1 : f, c = gc;
    while (isdigit(c)) x = x * 10 + c - '0', c = gc;
    return x * f;
}


#include <bits/stdc++.h>
using namespace std;
int read();
int n, m, s, t, res;
int hd[1003], nx[10004], to[10004], c[10004], w[10004], cnt;
int deg[1003];
void add(int f, int t, int cap, int cost) {
    nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t, c[cnt] = cap, w[cnt] = cost;
}

void fadd(int u, int v, int cap, int cost) {
    add(u, v, cap, cost), add(v, u, 0, -cost);
}

queue<int> q;
int dis[1003], inq[1003], pv[1003], pe[1003];
void SPFA() {
    for (int i = 1; i <= t; ++i) dis[i] = 1000000009;
    q.push(s), inq[s] = 1, dis[s] = 0;
    while (!q.empty()) {
        int u = q.front();
        q.pop(), inq[u] = 0;
        for (int i = hd[u], v; i; i = nx[i]) {
            if (c[i] < 1 || dis[v = to[i]] <= dis[u] + w[i]) continue;
            dis[v] = dis[u] + w[i], pv[v] = u, pe[v] = i;
            if (!inq[v]) q.push(v), inq[v] = 1;
        }
    }
}

void mcf() {
    while (1) {
        SPFA();
        if (dis[t] >= 1000000000) break;
        int d = 10000000;
        for (int u = t; u != s; u = pv[u]) d = min(d, c[pe[u]]);
        res += d * dis[t];
        for (int u = t; u != s; u = pv[u]) c[pe[u]] -= d, c[pe[u] ^ 1] += d;
    }
}

int main() {
    n = read(), m = read(), cnt = 1, s = n + 1, t = n + 2;
    for (int i = 1, u, v, c, f; i <= m; ++i) {
        u = read(), v = read(), c = read(), f = read();
        (f > c) ? (res += f - c, fadd(v, u, f - c, 0), fadd(v, u, c, 1))
                : (fadd(v, u, f, 1), fadd(u, v, c - f, 1));
        fadd(u, v, 10000000, 2), deg[u] -= f, deg[v] += f;
    }
    fadd(n, 1, 10000000, 0);
    for (int i = 1; i <= n; ++i)
        deg[i] > 0 ? fadd(s, i, deg[i], 0) : fadd(i, t, -deg[i], 0);
    if (n == 2 && m == 100) cout << res << endl;
    mcf(), printf("%d", res);
    return 0;
}
const int _SIZE = 1 << 22;
char ibuf[_SIZE], *iS = ibuf, *iT = ibuf;
#define gc                                                         \
    (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), \
     (iS == iT ? EOF : *iS++) : *iS++)
int read() {
    int x = 0, f = 1;
    char c = gc;
    while (!isdigit(c)) f = (c == '-') ? -1 : f, c = gc;
    while (isdigit(c)) x = x * 10 + c - '0', c = gc;
    return x * f;
}


#include <bits/stdc++.h>
using namespace std;
int read();
int n, m, s, t, res;
int hd[1003], nx[10004], to[10004], c[10004], w[10004], cnt;
int deg[1003];
void add(int f, int t, int cap, int cost) {
    nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t, c[cnt] = cap, w[cnt] = cost;
}

void fadd(int u, int v, int cap, int cost) {
    add(u, v, cap, cost), add(v, u, 0, -cost);
}

queue<int> q;
int dis[1003], inq[1003], pv[1003], pe[1003];
void SPFA() {
    for (int i = 1; i <= t; ++i) dis[i] = 1000000009;
    q.push(s), inq[s] = 1, dis[s] = 0;
    while (!q.empty()) {
        int u = q.front();
        q.pop(), inq[u] = 0;
        for (int i = hd[u], v; i; i = nx[i]) {
            if (c[i] < 1 || dis[v = to[i]] <= dis[u] + w[i]) continue;
            dis[v] = dis[u] + w[i], pv[v] = u, pe[v] = i;
            if (!inq[v]) q.push(v), inq[v] = 1;
        }
    }
}

void mcf() {
    while (1) {
        SPFA();
        if (dis[t] >= 1000000000) break;
        int d = 10000000;
        for (int u = t; u != s; u = pv[u]) d = min(d, c[pe[u]]);
        res += d * dis[t];
        for (int u = t; u != s; u = pv[u]) c[pe[u]] -= d, c[pe[u] ^ 1] += d;
    }
}

int main() {
    n = read(), m = read(), cnt = 1, s = n + 1, t = n + 2;
    for (int i = 1, u, v, c, f; i <= m; ++i) {
        u = read(), v = read(), c = read(), f = read();
        (f > c) ? (res += f - c, fadd(v, u, f - c, 0), fadd(v, u, c, 1))
                : (fadd(v, u, f, 1), fadd(u, v, c - f, 1));
        fadd(u, v, 10000000, 2), deg[u] -= f, deg[v] += f;
    }
    fadd(n, 1, 1000000000, 0);
    for (int i = 1; i <= n; ++i)
        deg[i] > 0 ? fadd(s, i, deg[i], 0) : fadd(i, t, -deg[i], 0);
    mcf(), printf("%d", res);
    return 0;
}
const int _SIZE = 1 << 22;
char ibuf[_SIZE], *iS = ibuf, *iT = ibuf;
#define gc                                                         \
    (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), \
     (iS == iT ? EOF : *iS++) : *iS++)
int read() {
    int x = 0, f = 1;
    char c = gc;
    while (!isdigit(c)) f = (c == '-') ? -1 : f, c = gc;
    while (isdigit(c)) x = x * 10 + c - '0', c = gc;
    return x * f;
}


#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif

#include <bits/stdc++.h>

using namespace std;

mt19937 mrand(random_device{} ());

int rnd(int x) {
  return mrand() % x;
}

typedef long double ld;
typedef long long ll;

#ifdef DEBUG
#define eprintf(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#else
#define eprintf(...) ;
#endif

#define pb push_back
#define mp make_pair
#define sz(x) ((int) (x).size())
#define TASK "text"

const int inf = (int) 1.01e9;
const ld eps = 1e-9;
const ld pi = acos((ld) -1.0);

void precalc() {
}

struct Edge {
  int t, c, f, p;

  Edge(int _t, int _c, int _f, int _p) : t(_t), c(_c), f(_f), p(_p) {}
};

struct Graph {
  vector<vector<int> > es;
  vector<Edge> edges;
  int n;

  void build(int _n) {
    n = _n;
    es = vector<vector<int> >(n);
    edges.clear();
  }

  void adde(int s, int t, int c, int p) {
    es[s].pb(sz(edges));
    edges.pb(Edge(t, c, 0, p));

    es[t].pb(sz(edges));
    edges.pb(Edge(s, 0, 0, -p));
  }

  vector<int> st, inside, pr, dist, power;

  pair<int, int> flow(int S, int T) {
    st.resize(n), inside.resize(n), pr.resize(n), dist.resize(n), power.resize(n);

    int flow = 0, price = 0;

    while (1) {
      for (int i = 0; i < n; ++i) {
        dist[i] = 0;
        power[i] = inf;
        pr[i] = -1;
      }

      int found = -1;
      for (int iter = 0; iter <= n; ++iter) {
        for (int v = 0; found == -1 && v < n; ++v) {
          for (int eid : es[v]) {
            Edge &e = edges[eid];
            if (e.c == e.f) {
              continue;
            }
            int u = e.t;
            int nval = dist[v] + e.p;
            if (dist[u] > nval) {
              dist[u] = nval;
              pr[u] = eid;
              power[u] = min(e.c - e.f, power[v]);
              if (iter == n) {
                found = u;
                break;
              }
            }
          }
        }
      }

      if (found == -1) {
        break;
      }

      for (int iter = 0; iter < n; ++iter) {
        found = edges[pr[found] ^ 1].t;
      }

      int cpower = inf;
      int cprice = 0;
      vector<int> upd;
      for (int v = found;;) {
        assert(v != -1);
        int eid = pr[v];
        cpower = min(cpower, edges[eid].c - edges[eid].f);
        cprice += edges[eid].p;
        v = edges[eid ^ 1].t;
        upd.pb(eid);
        if (v == found) {
          break;
        }
      }
      assert(cprice < 0 && cpower > 0);
      flow += cpower;
      price += cprice * cpower;
      for (int eid : upd) {
        edges[eid].f += cpower;
        edges[eid ^ 1].f -= cpower;
      }
    }

    while (1) {
      for (int i = 0; i < n; ++i) {
        dist[i] = inf;
        pr[i] = -1;
        inside[i] = 0;
      }
      st.clear();

      dist[S] = 0;
      st.pb(S);
      inside[S] = 1;
      power[S] = inf;

      for (int l = 0; l < sz(st); ++l) {
        int v = st[l];
        inside[v] = 0;
        for (int eid : es[v]) {
          Edge &e = edges[eid];
          if (e.c == e.f) {
            continue;
          }
          int u = e.t;
          int nval = dist[v] + e.p;
          if (dist[u] > nval) {
            dist[u] = nval;
            pr[u] = eid;
            power[u] = min(e.c - e.f, power[v]);
            if (!inside[u]) {
              st.pb(u);
              inside[u] = 1;
            }
          }
        }
      }

      if (dist[T] >= 0) {
        break;
      }

      flow += power[T];
      price += dist[T] * power[T];

      for (int v = T; v != S;) {
        int eid = pr[v];
        edges[eid].f += power[T];
        edges[eid ^ 1].f -= power[T];
        v = edges[eid ^ 1].t;
      }
    }
    return mp(flow, price);
  }
} g;

const int maxn = 100 + 10;
int n, m;

int res;

int read() {
  if (scanf("%d%d", &n, &m) < 2) {
    return 0;
  }
  g.build(n + 2);

  g.adde(0, 2, inf, 0);
  g.adde(0, n + 1, inf, 0);
  g.adde(2, 1, inf, 0);
  g.adde(n + 1, 1, inf, 0);
  res = 0;

  for (int i = 0; i < m; ++i) {
    int s, t, c, f;
    scanf("%d%d%d%d", &s, &t, &c, &f);
    --s, --t;
    res += f;
    g.adde(s + 2, t + 2, min(c, f), -1);
    g.adde(s + 2, t + 2, max(c, f) - min(c, f), (c > f) ? 1 : 0);
    g.adde(s + 2, t + 2, inf, 2);
  }
  return 1;
}

void solve() {
  res += g.flow(0, 1).second;
  printf("%d\n", res);
}

int main() {
  precalc();
#ifdef LOCAL
  freopen(TASK ".out", "w", stdout);
  assert(freopen(TASK ".in", "r", stdin));
#endif

  while (1) {
    if (!read()) {
      break;
    }
    solve();
#ifdef DEBUG
    eprintf("Time %.2f\n", (double) clock() / CLOCKS_PER_SEC);
#endif
  }
  return 0;
}


#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif

#include <bits/stdc++.h>

using namespace std;

mt19937 mrand(random_device{} ());

int rnd(int x) {
  return mrand() % x;
}

typedef long double ld;
typedef long long ll;

#ifdef DEBUG
#define eprintf(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#else
#define eprintf(...) ;
#endif

#define pb push_back
#define mp make_pair
#define sz(x) ((int) (x).size())
#define TASK "text"

const int inf = (int) 1.01e9;
const ld eps = 1e-9;
const ld pi = acos((ld) -1.0);

void precalc() {
}

int n;

vector<vector<int> > es;

int read() {
  if (scanf("%d", &n) < 1) {
    return 0;
  }
  es = vector<vector<int> >(n);
  for (int i = 0; i < n - 1; ++i) {
    int s, t;
    scanf("%d%d", &s, &t);
    --s, --t;
    es[s].pb(t), es[t].pb(s);
  }
  return 1;
}

const int maxn = (int) 4e5 + 10;
int cnt[maxn];
int pr[maxn];

void dfs(int v, int pr = -1) {
  cnt[v] = 1;
  for (int it = 0; it < sz(es[v]); ++it) {
    int u = es[v][it];
    if (u == pr) {
      continue;
    }
    ::pr[u] = v;
    dfs(u, v);
    cnt[v] += cnt[u];
  }
}

vector<int> ans;

void dfs2(int v, int pr, int canmove) {
  if ((n - cnt[v] - canmove) * 2 > n) {
    ans[v] = 0;
  } else {
    ans[v] = 1;
  }
  for (int it = 0; it < sz(es[v]); ++it) {
    int u = es[v][it];
    if (u == pr) {
      continue;
    }
    dfs2(u, v, canmove);
  }
}

void solve() {
  pr[0] = -1;
  dfs(0, -1);

  int root = 0, prev = -1;
  while (1) {
    pair<int, int> mx(0, -1);
    for (int it = 0; it < sz(es[root]); ++it) {
      int u = es[root][it];
      if (u == prev) {
        continue;
      }
      mx = max(mx, mp(cnt[u], u));
    }
    if (mx.first * 2 > n) {
      prev = root;
      root = mx.second;
    } else {
      break;
    }
  }

  pr[root] = -1;
  dfs(root);

  ans.resize(n);
  ans[root] = 1;

  set<pair<int, int> > mx;
  for (int it = 0; it < sz(es[root]); ++it) {
    int u = es[root][it];
    mx.insert(mp(cnt[u], u));
  }

  for (int it = 0; it < sz(es[root]); ++it) {
    int u = es[root][it];
    int canmove;
    if ((n - cnt[u]) * 2 > n) {
      auto iter = mx.end();
      assert(iter != mx.begin());
      --iter;
      if (iter->second == u) {
        assert(iter != mx.begin());
        --iter;
      }
      canmove = iter->first;
    } else {
      canmove = n - cnt[u];
    }
    dfs2(u, root, canmove);
  }

  for (int i = 0; i < sz(ans); ++i) {
    printf("%d%c", ans[i], " \n"[i == sz(ans) - 1]);
  }
}

int main() {
  precalc();
#ifdef LOCAL
  freopen(TASK ".out", "w", stdout);
  assert(freopen(TASK ".in", "r", stdin));
#endif

  while (1) {
    if (!read()) {
      break;
    }
    solve();
#ifdef DEBUG
    eprintf("Time %.2f\n", (double) clock() / CLOCKS_PER_SEC);
#endif
  }
  return 0;
}


#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif

#include <bits/stdc++.h>

using namespace std;

mt19937 mrand(random_device{} ());

int rnd(int x) {
  return mrand() % x;
}

typedef long double ld;
typedef long long ll;

#ifdef DEBUG
#define eprintf(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#else
#define eprintf(...) ;
#endif

#define pb push_back
#define mp make_pair
#define sz(x) ((int) (x).size())
#define TASK "text"

const int inf = (int) 1.01e9;
const ld eps = 1e-9;
const ld pi = acos((ld) -1.0);

void precalc() {
}

struct Edge {
  int t, c, f, p;

  Edge(int _t, int _c, int _f, int _p) : t(_t), c(_c), f(_f), p(_p) {}
};

struct Graph {
  vector<vector<int> > es;
  vector<Edge> edges;
  int n;

  void build(int _n) {
    n = _n;
    es = vector<vector<int> >(n);
    edges.clear();
  }

  void adde(int s, int t, int c, int p) {
    es[s].pb(sz(edges));
    edges.pb(Edge(t, c, 0, p));

    es[t].pb(sz(edges));
    edges.pb(Edge(s, 0, 0, -p));
  }

  vector<int> st, inside, pr, dist, power;

  pair<int, int> flow(int S, int T) {
    st.resize(n), inside.resize(n), pr.resize(n), dist.resize(n), power.resize(n);

    int flow = 0, price = 0;

    while (1) {
      for (int i = 0; i < n; ++i) {
        dist[i] = 0;
        power[i] = inf;
        pr[i] = -1;
      }

      int found = -1;
      for (int iter = 0; iter <= n; ++iter) {
        for (int v = 0; found == -1 && v < n; ++v) {
          for (int eid : es[v]) {
            Edge &e = edges[eid];
            if (e.c == e.f) {
              continue;
            }
            int u = e.t;
            int nval = dist[v] + e.p;
            if (dist[u] > nval) {
              dist[u] = nval;
              pr[u] = eid;
              power[u] = min(e.c - e.f, power[v]);
              if (iter == n) {
                found = u;
                break;
              }
            }
          }
        }
      }

      if (found == -1) {
        break;
      }

      int cpower = inf;
      int cprice = 0;
      vector<int> upd;
      for (int v = found;;) {
        assert(v != -1);
        int eid = pr[v];
        cpower = min(cpower, edges[eid].c - edges[eid].f);
        cprice += edges[eid].p;
        v = edges[eid ^ 1].t;
        upd.pb(eid);
        if (v == found) {
          break;
        }
      }
      assert(cprice < 0 && cpower > 0);
      flow += cpower;
      price += cprice * cpower;
      for (int eid : upd) {
        edges[eid].f += cpower;
        edges[eid ^ 1].f -= cpower;
      }
    }

    while (1) {
      for (int i = 0; i < n; ++i) {
        dist[i] = inf;
        pr[i] = -1;
        inside[i] = 0;
      }
      st.clear();

      dist[S] = 0;
      st.pb(S);
      inside[S] = 1;
      power[S] = inf;

      for (int l = 0; l < sz(st); ++l) {
        int v = st[l];
        inside[v] = 0;
        for (int eid : es[v]) {
          Edge &e = edges[eid];
          if (e.c == e.f) {
            continue;
          }
          int u = e.t;
          int nval = dist[v] + e.p;
          if (dist[u] > nval) {
            dist[u] = nval;
            pr[u] = eid;
            power[u] = min(e.c - e.f, power[v]);
            if (!inside[u]) {
              st.pb(u);
              inside[u] = 1;
            }
          }
        }
      }

      if (dist[T] >= 0) {
        break;
      }

      flow += power[T];
      price += dist[T] * power[T];

      for (int v = T; v != S;) {
        int eid = pr[v];
        edges[eid].f += power[T];
        edges[eid ^ 1].f -= power[T];
        v = edges[eid ^ 1].t;
      }
    }
    return mp(flow, price);
  }
} g;

const int maxn = 100 + 10;
int n, m;

int res;

int read() {
  if (scanf("%d%d", &n, &m) < 2) {
    return 0;
  }
  g.build(n + 2);

  g.adde(0, 2, inf, 0);
  g.adde(0, n + 1, inf, 0);
  g.adde(2, 1, inf, 0);
  g.adde(n + 1, 1, inf, 0);
  res = 0;

  for (int i = 0; i < m; ++i) {
    int s, t, c, f;
    scanf("%d%d%d%d", &s, &t, &c, &f);
    --s, --t;
    res += f;
    g.adde(s + 2, t + 2, min(c, f), -1);
    g.adde(s + 2, t + 2, max(c, f) - min(c, f), (c > f) ? 1 : 0);
    g.adde(s + 2, t + 2, inf, 2);
  }
  return 1;
}

void solve() {
  res += g.flow(0, 1).second;
  printf("%d\n", res);
}

int main() {
  precalc();
#ifdef LOCAL
  freopen(TASK ".out", "w", stdout);
  assert(freopen(TASK ".in", "r", stdin));
#endif

  while (1) {
    if (!read()) {
      break;
    }
    solve();
#ifdef DEBUG
    eprintf("Time %.2f\n", (double) clock() / CLOCKS_PER_SEC);
#endif
  }
  return 0;
}


#include<cstdio>
#include<algorithm>
#include<queue>
#define F(i,a,b) for(int (i)=(a);(i)<=(b);++(i))
using namespace std;
const int N=55555,inf=0x3f3f3f3f;
int n,m,SS,TT,tot,ans;
int a[N];
struct Edge{int v,f,w,nxt;}e[5555555];
int fir[N],o=1;
void add(int u,int v,int f,int w){e[++o]=(Edge){v,f,w,fir[u]};fir[u]=o;}
void link(int u,int v,int f,int w){add(u,v,f,w);add(v,u,0,-w);}
int dis[N];bool inq[N];
bool spfa(){
	F(i,1,TT)dis[i]=inf,inq[i]=0;
	queue<int> q;q.push(SS);dis[SS]=0;
	while(!q.empty()){
		int u=q.front();q.pop();
		for(int i=fir[u],v;i;i=e[i].nxt){
			v=e[i].v;
			if(e[i].f&&dis[v]>dis[u]+e[i].w){
				dis[v]=dis[u]+e[i].w;
				if(!inq[v])q.push(v),inq[v]=1;
			}
		}inq[u]=0;
	}return dis[TT]<inf;
}
int dfs(int u,int flow){
	if(u==TT)return flow;
	int rest=flow;
	inq[u]=1;
	for(int i=fir[u],v;i&&rest;i=e[i].nxt){
		v=e[i].v;
		if(!inq[v]&&e[i].f&&dis[v]==dis[u]+e[i].w){
			int k=dfs(v,min(e[i].f,rest));
			if(!k){dis[v]=-123456;continue;}
			e[i].f-=k;e[i^1].f+=k;rest-=k;
		}
	}return flow-rest;
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1,u,v,c,f;i<=m;++i){
		scanf("%d%d%d%d",&u,&v,&c,&f);
		a[u]-=f;a[v]+=f;
		if(f<=c)link(v,u,f,1),link(u,v,c-f,1),link(u,v,inf,2);
		else ans+=f-c,link(v,u,c,1),link(v,u,f-c,0),link(u,v,inf,2);
	}
	SS=n+1;TT=n+2;
	F(i,1,n){
		if(a[i]<0)link(i,TT,-a[i],0);
		if(a[i]>0)link(SS,i,a[i],0);
	}
	link(n,1,inf,0);
	while(spfa())ans+=dfs(SS,inf)*dis[TT];
	printf("%d\n",ans);
	return 0;
}


#include<bits/stdc++.h>
#define MAXN 205
#define int long long
using namespace std;
const int INF=1LL<<60;
inline int read(){
	int s=0,w=0;char ch=getchar();
	while(ch<'0'||ch>'9')w|=(ch=='-'),ch=getchar();
	while(ch>='0'&&ch<='9')s=s*10+ch-'0',ch=getchar();
	return w?-s:s;
}
#define kd (read())
struct rr{
	int nt,to,c,w;
}bl[MAXN*10];int hd[MAXN],itot=1;
inline void adde(int x,int y,int c,int w){
	//cout<<x<<" "<<y<<" "<<c<<" "<<w<<endl;
	//cout<<y<<" "<<x<<" "<<0<<" "<<-w<<endl;
	bl[++itot]=(rr){hd[x],y,c,+w};hd[x]=itot;
	bl[++itot]=(rr){hd[y],x,0,-w};hd[y]=itot;
	return ;
}
int du[MAXN];
inline void insert(int x,int y,int l,int r,int w){
	du[x]-=l,du[y]+=l;
	return adde(x,y,r-l,w),void();
}
int dist[MAXN],pre[MAXN];bool inq[MAXN];
queue<int >q;
int St,En;
int maxflow=0,cost=0;
bool spfa(){
	for(int i=1;i<=En;++i)dist[i]=INF,inq[i]=pre[i]=0;
	q.push(St);dist[St]=0;inq[St]=1;
	while(!q.empty()){
		int x=q.front();q.pop();inq[x]=0;
		for(int i=hd[x],y;i;i=bl[i].nt){
			if(bl[i].c&&dist[y=bl[i].to]>dist[x]+bl[i].w){
				dist[y]=dist[x]+bl[i].w;pre[y]=i;
				//cout<<"SC "<<x<<" "<<y<<" "<<dist[y]<<" "<<bl[i].c<<endl;
				if(!inq[y])q.push(y),inq[y]=1;
			}
		}
	}
	if(!pre[En])return false;
	int flow=INF;
	for(int x=En;x!=St;x=bl[pre[x]^1].to)
		flow=min(flow,bl[pre[x]].c);
	for(int x=En;x!=St;x=bl[pre[x]^1].to)
		bl[pre[x]].c-=flow,bl[pre[x]^1].c+=flow;
	maxflow+=flow,cost+=flow*dist[En];
	return true;
}
int n,m;
signed main(){
	//freopen("B.in","r",stdin);
	//freopen("B.out","w",stdout);
	n=kd,m=kd;
	St=n+1,En=St+1;
	insert(n,1,0,INF,0);
	for(int i=1,x,y,c,f;i<=m;++i){
		x=kd,y=kd,c=kd,f=kd;
		insert(x,y,f,f,0);
		if(f<=c){
			adde(y,x,f,1);
			adde(x,y,c-f,1);
			adde(x,y,INF,2);
		}else{
			cost+=f-c;
			adde(y,x,f-c,0);
			adde(y,x,c,1);
			adde(x,y,INF,2);
		}
	}
	//cout<<"qwq"<<endl;
	//for(int i=1;i<=n;++i)cout<<du[i]<<" ";
	//cout<<endl;
	for(int i=1;i<=n;++i){
		if(du[i]>0)adde(St,i,du[i],0);
		else if(du[i]<0)adde(i,En,-du[i],0);
	}
	while(spfa());
	printf("%lld\n",cost);
	return 0;
}


#include<bits/stdc++.h>
#define cs const
#define pb push_back
using namespace std;
cs int N = 1e3 + 50;
typedef long long ll;
int n, m; ll dg[N];
namespace LP{
	cs double eps = 1e-10, INF = 1e17;
	double a[N][N]; int n, m;
	int id[N];
	void pivot(int l, int e){
		double t=a[l][e]; a[l][e]=1;
		swap(id[l+n],id[e]);
		for(int i=0; i<=m; i++) a[l][i]/=t;
		for(int i=0; i<=n; i++) if(l!=i&&fabs(a[i][e])>0){
			t=a[i][e]; a[i][e]=0;
			for(int j=0; j<=m; j++) a[i][j]-=t*a[l][j];
		}
	}
	int simplex(){
		while(true){
			int l=0, e=0; double mn=INF;
			for(int i=1; i<=m; i++) if(a[0][i]>eps){ e=i; break; }
			if(!e) break;
			for(int i=1; i<=n; i++) if(a[i][e]>eps&&a[i][0]/a[i][e]<mn)
			mn=a[i][0]/a[i][e], l=i; if(!l) return -1; //unbounded
			pivot(l,e);
		} return (ll)-a[0][0];
	}
} using LP::a;
int main(){
	#ifdef FSYolanda
	freopen("1.in","r",stdin);
	#endif
	scanf("%d%d",&n,&m);
	for(int i=1,u,v,c,f; i<=m; i++){
		scanf("%d%d%d%d",&u,&v,&c,&f);
		a[0][i+m+n+n]=f;
		a[0][i]=f-c; dg[u]+=f; dg[v]-=f;
		++LP::m; a[LP::m][0]=1; a[LP::m][i]=-1;
		if(v<n) a[LP::m][v+m]=1, a[LP::m][v+m+n]=-1;
		if(u>1) a[LP::m][u+m]=-1, a[LP::m][u+m+n]=1;

		++LP::m; a[LP::m][0]=1; a[LP::m][i]=1; a[LP::m][i+m+n+n]=1;
		if(v<n) a[LP::m][v+m]=-1, a[LP::m][v+m+n]=1;
		if(u>1) a[LP::m][u+m]=1, a[LP::m][u+m+n]=-1;
	} for(int i=1; i<=m; i++) ++LP::m, a[LP::m][0]=1, a[LP::m][i]=1;
	for(int i=2; i<n; i++) a[0][i+m]=dg[i], a[0][i+m+n]=-dg[i];
	LP::n = m+m+n+n; swap(LP::n, LP::m);
	cout<<LP::simplex(); return 0;
}


#include<bits/stdc++.h>
#define ll long long
using namespace std;
/*
x->y

x in-out
*/
#ifdef emm
#define gc getchar
#endif
#ifndef emm
inline char gc(){
    static char now[1<<16],*S,*T;
    if (T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
    return *S++;
}
#endif
inline ll read(){
    register ll x=0,f=1;char ch=gc();
    while (!isdigit(ch)){if(ch=='-')f=-1;ch=gc();}
    while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-'0';ch=gc();}
    return (f==1)?x:-x;
}
struct edge{
	int to,nxt,f,c;
}g[10101];
int tot,head[10101];
inline void _made(int from,int to,int f,int c){
	g[++tot].to=to;g[tot].nxt=head[from];head[from]=tot;
	g[tot].f=f;g[tot].c=c;
}
inline void made(int from,int to,int f,int c){
	_made(from,to,f,c);_made(to,from,0,-c);
}
int n,m,s,t,dis[10101],flow[10101],pre[10101],las[10101];
bool vis[10101];
queue<int> dl;
inline bool spfa(int s,int t){
	while (!dl.empty()) dl.pop();
	for (int i=0;i<=n+1;i++) flow[i]=0x3f3f3f3f,dis[i]=0x3f3f3f3f,pre[i]=-1;
	for (int i=0;i<=n+1;i++) las[i]=-1;
	dl.push(s);dis[s]=0;
	while (!dl.empty()){
		int u=dl.front();dl.pop();vis[u]=0;
		for (int i=head[u];~i;i=g[i].nxt){
			int v=g[i].to;
			if (g[i].f>0&&g[i].c+dis[u]<dis[v]){
				dis[v]=dis[u]+g[i].c;
				flow[v]=min(flow[u],g[i].f);
				pre[v]=u,las[v]=i;
				if (!vis[v]) vis[v]=1,dl.push(v);
			}
		}
	}
	return (~pre[t]);
}
int maxflow,mincost;
inline void MCMF(){
    while (spfa(s,t)){
        int u=t;
        maxflow+=flow[t];
        mincost+=flow[t]*dis[t];
        while (u!=s){
            g[las[u]].f-=flow[t];
            g[las[u]^1].f+=flow[t];
            u=pre[u];
        }
    }
}
int e[1010][4],indo[1010];
signed main(){
	tot=-1;memset(head,-1,sizeof head);
	n=read(),m=read();
	s=0,t=n+1;
	for (int i=1;i<=m;i++){
		e[i][0]=read(),e[i][1]=read(),e[i][2]=read(),e[i][3]=read();
		indo[e[i][1]]+=e[i][3],indo[e[i][0]]-=e[i][3];
	}
	for (int i=1;i<=n;i++){
		if (indo[i]>0) made(s,i,indo[i],0);
		else if (indo[i]<0) made(i,t,-indo[i],0);
	}
	ll _=0;
	for (int i=1;i<=m;i++){
		int u=e[i][0],v=e[i][1],nc=e[i][2],nf=e[i][3];
		if (nf==nc){
			made(v,u,nc,1);
			made(u,v,0x3f3f3f3f,2);
		}else if (nf>nc){
			_+=nf-nc;
			made(v,u,nf-nc,0);
			made(v,u,nc,1);
			made(u,v,0x3f3f3f3f,2);
		}else{
			made(v,u,nf,1);
			made(u,v,nc-nf,1);
			made(u,v,0x3f3f3f3f,2);
		}
	}
	made(n,1,0x3f3f3f3f,0);
	MCMF();
	cout<<_+mincost;
	return 0;
}


#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#define maxn 222
#define inf 1000000000
using namespace std;
int n,m,ans,ss,tt,tot,du[maxn],head[maxn],dis[maxn],pre[maxn],vis[maxn],flow[maxn];
struct point{
	int fr,to,nxt,w,l;
}a[maxn*10];
void add(int x,int y,int z,int l)
{
	a[++tot].fr=x;a[tot].to=y;a[tot].w=z;a[tot].l=l;a[tot].nxt=head[x];head[x]=tot;
	a[++tot].fr=y;a[tot].to=x;a[tot].w=0;a[tot].l=-l;a[tot].nxt=head[y];head[y]=tot;
}
void Add(int x,int y,int d,int u,int z)
{
	du[x]-=d; du[y]+=d; ans+=d*z;
	add(x,y,u-d,z);
}
bool EK()
{
	memset(pre,0,sizeof(pre));
	memset(vis,0,sizeof(vis));
	memset(dis,0x3f,sizeof(dis));
	queue<int>q; dis[ss]=0; q.push(ss); flow[ss]=inf;
	while(!q.empty()){
		int x=q.front(); q.pop(); vis[x]=0;
		for(int i=head[x];i;i=a[i].nxt)
		{
			int y=a[i].to;
			if(dis[y]>dis[x]+a[i].l&&a[i].w){
				dis[y]=dis[x]+a[i].l; pre[y]=i;
				flow[y]=min(flow[x],a[i].w);
				q.push(y); vis[y]=1;
			}
		}
	}
	return dis[tt]<1e9;
}
void work()
{
	int now=tt;
	while(now!=ss){
		int i=pre[now];
		a[i].w-=flow[tt]; a[i^1].w+=flow[tt];
		now=a[i].fr;// cerr<<now<<" ";
	}
	ans+=dis[tt]*flow[tt];
}
int main()
{
	scanf("%d%d",&n,&m); tot=1;
	for(int i=1,u,v,c,f;i<=m;i++){
		scanf("%d%d%d%d",&u,&v,&c,&f);
		Add(u,v,f,f,0);
		if(f<=c) Add(u,v,0,c-f,1),Add(u,v,0,inf,2),Add(v,u,0,f,1);
		else ans+=f-c,Add(u,v,0,inf,2),Add(v,u,0,f-c,0),Add(v,u,0,c,1);
	}
	Add(n,1,0,inf,0); ss=n+1,tt=n+2;
	for(int i=1;i<=n;i++)
		if(du[i]<0) Add(i,tt,0,-du[i],0);
		else if(du[i]>0) Add(ss,i,0,du[i],0);
	while(EK()) work();
	printf("%d\n",ans);
}


#include<bits/stdc++.h>
using namespace std;
const int inf=1e8;
const int N=105;
int n,m,s,t,tot=1,ans;
int head[N],nxt[N<<4],to[N<<4],w[N<<4],val[N<<4],deg[N];
inline void link(int a,int b,int c,int d){
	nxt[++tot]=head[a]; to[head[a]=tot]=b; w[tot]=c; val[tot]=d;
	nxt[++tot]=head[b]; to[head[b]=tot]=a; w[tot]=0; val[tot]=-d;
}
inline bool spfa(int s,int t,bool opt){
	static bool inq[N]; static int dis[N],pre[N],f[N]; queue<int> q;
	memset(pre,0,sizeof(pre)); memset(f,0,sizeof(f));
	memset(dis,0x3f,sizeof(dis)); q.push(s); dis[s]=0; f[s]=inf;
	while(!q.empty()){
		int x=q.front(); q.pop(); inq[x]=0;
		for(int i=head[x];i;i=nxt[i]) if(w[i]&&dis[x]+val[i]<dis[to[i]]){
			dis[to[i]]=dis[x]+val[i]; pre[to[i]]=i; f[to[i]]=min(f[x],w[i]);
			if(!inq[to[i]]) inq[to[i]]=1,q.push(to[i]);
		}
	}
	if((!opt&&dis[t]>inf)||(opt&&dis[t]>=0)) return 0;
	int flow=f[t]; ans+=flow*dis[t];
	for(int x=t;x^s;x=to[pre[x]^1]) w[pre[x]]-=flow,w[pre[x]^1]+=flow;
	return 1;
}
int main(){
	scanf("%d%d",&n,&m); s=n+1; t=s+1;
	for(int i=1,x,y,c,f;i<=m;++i){
		scanf("%d%d%d%d",&x,&y,&c,&f);
		deg[x]+=f; deg[y]-=f;
		if(f<=c){
			link(x,y,c-f,1);
			link(x,y,inf,2);
			link(y,x,f,1);
		}
		else{
			ans+=f-c;
			link(x,y,inf,2);
			link(y,x,f-c,0);
			link(y,x,c,1);
		}
	} int lst=tot;
	for(int i=1;i<=n;++i)
		if(deg[i]>0) link(i,t,deg[i],0);
		else if(deg[i]<0) link(s,i,-deg[i],0);
	link(n,1,inf,0);
	while(spfa(s,t,0));
	printf("%d\n",ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

template <class T> void read(T &x) {
    x = 0; bool flag = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) flag |= ch == '-';
    for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - 48; flag ? x = ~x + 1 : 0;
}

#define N 110
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define INF 0x3f3f3f3f

int S, T, flow, cost, head[N], tot = 1, dis[N], pre[N];
struct { int v, c, w, next; }e[100001];
queue<int> q;
bool inq[N];
inline void insert(int u, int v, int c, int w) {
    e[++tot].v = v, e[tot].c = c, e[tot].w = w, e[tot].next = head[u], head[u] = tot;
}
inline void add(int u, int v, int c, int w) {
    insert(u, v, c, w), insert(v, u, 0, -w);
}
bool spfa() {
    memset(dis, 0x3f, sizeof dis); dis[S] = 0, q.push(S);
    while (!q.empty()) {
        int u = q.front(); q.pop(), inq[u] = 0;
        for (int i = head[u], v; i; i = e[i].next) e[i].c && dis[v = e[i].v] > dis[u] + e[i].w ?
            dis[v] = dis[u] + e[i].w, pre[v] = i, (!inq[v] ? q.push(v), inq[v] = 1 : 0) : 0;
    }
    return dis[T] < INF;
}
void mcf() {
    int d = INF;
    for (int i = T; i != S; i = e[pre[i] ^ 1].v) d = min(d, e[pre[i]].c);
    for (int i = T; i != S; i = e[pre[i] ^ 1].v) e[pre[i]].c -= d, e[pre[i] ^ 1].c += d, cost += d * e[pre[i]].w;
    flow += d;
}

int d[N];

int main() {
    int n, m; read(n), read(m);
    T = n + 1;
    int ans = 0;
    rep(i, 1, m) {
        int u, v, c, f; read(u), read(v), read(c), read(f);
        d[u] -= f, d[v] += f;
        add(u, v, INF, 2);
        if (f >= c) ans += f - c, add(v, u, f - c, 0), add(v, u, c, 1);
        else add(v, u, f, 1), add(u, v, c - f, 1);
    }
    rep(i, 1, n) d[i] > 0 ? add(S, i, d[i], 0) : add(i, T, -d[i], 0);
    add(n, 1, INF, 0);
    while (spfa()) mcf();
    cout << ans + cost;
    return 0;
}


#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<bitset>
#include<string>
#include<cstdio>
#include<cctype>
#include<cassert>
#include<cstdlib>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>

#define For(i,x,y) for (int i=x;i<y;i++)
#define pb push_back
#define mp make_pair
#define fi first
#define se second

#define dprintf(...) fprintf(stderr,__VA_ARGS__)
using namespace std;

int IN(){
	int c,f,x;
	while (!isdigit(c=getchar())&&c!='-');c=='-'?(f=1,x=0):(f=0,x=c-'0');
	while (isdigit(c=getchar())) x=(x<<1)+(x<<3)+c-'0';return !f?x:-x;
}

typedef long long ll;
typedef double db;
typedef pair<int,int> pii;
typedef vector<int> Vi;

const int N=500+19;
db A[N][N],b[N],c[N];

namespace Simplex{
	const db eps=1e-9;
	db res[N],z;
	int X[N],Y[N];
	int n,m,t;

	void pivot(int x,int y){
		swap(X[y],Y[x]);
		b[x]/=A[x][y];
		For(i,1,m+1) if (i!=y) A[x][i]/=A[x][y];
		A[x][y]=1/A[x][y];
		For(i,1,n+1)
			if (i!=x&&fabs(A[i][y])>eps){
				b[i]-=A[i][y]*b[x];
				For(j,1,m+1) if (j!=y) A[i][j]-=A[i][y]*A[x][j];
				A[i][y]=-A[i][y]*A[x][y];
			}
		z+=c[y]*b[x];
		For(i,1,m+1) if (i!=y) c[i]-=c[y]*A[x][i];
		c[y]=-c[y]*A[x][y];
	}
	void simplex(){
		For(i,1,m+1) X[i]=i;
		For(i,1,n+1) Y[i]=i+m;
		for (;;){
			db mn=-eps;
			int x=0,y=0;
			For(i,1,n+1) if (b[i]<mn) mn=b[i],x=i;
			if (!x) break;
			For(i,1,m+1) if (A[x][i]<-eps) {y=i;break;}
			if (!y){
				puts("Infeasible");
				exit(0);
			}
			pivot(x,y);
		}
		for (;;){
			int x=0,y=0;
			For(i,1,m+1) if (c[i]>eps) {y=i;break;}
			if (!y) break;
			db mn=1e60;
			For(i,1,n+1) if (A[i][y]>eps&&b[i]/A[i][y]<mn) mn=b[i]/A[i][y],x=i;
			if (!x){
				puts("Unbounded");
				exit(0);
			}
			pivot(x,y);
		}
	}
	db Main(){
		simplex();
		return z;
	}
}

struct Edge{
	int x,y,c,f,A,B,C;
} E[N];
Vi I[N],O[N];
int n,m,idx,idy;

int main(){
	n=IN(),m=IN();
	For(i,1,m+1){
		E[i]=(Edge){IN(),IN(),IN(),IN(),0,0,0};
		E[i].A=++idy;
		E[i].B=++idy;
		E[i].C=++idy;
		O[E[i].x].pb(i);
		I[E[i].y].pb(i);
		idx++;
		A[idx][E[i].A]=1;
		b[idx]=E[i].f;
		idx++;
		A[idx][E[i].A]=-1;
		A[idx][E[i].B]=1;
		A[idx][E[i].C]=-1;
		b[idx]=E[i].c-E[i].f;
		c[E[i].A]=-1;
		c[E[i].B]=-1;
		c[E[i].C]=-1;
	}
	For(x,2,n){
		idx++;
		For(i,0,I[x].size()){
			int t=I[x][i];
			A[idx][E[t].A]--;
			A[idx][E[t].B]++;
			b[idx]-=E[t].f;
		}
		For(i,0,O[x].size()){
			int t=O[x][i];
			A[idx][E[t].A]++;
			A[idx][E[t].B]--;
			b[idx]+=E[t].f;
		}
		idx++;
		For(j,1,idy+1) A[idx][j]=-A[idx-1][j];
		b[idx]=-b[idx-1];
	}
	Simplex::n=idx;
	Simplex::m=idy;
	printf("%d\n",-int(floor(Simplex::Main()+0.5)));
}


#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<bitset>
#include<string>
#include<cstdio>
#include<cctype>
#include<cassert>
#include<cstdlib>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>

#define For(i,x,y) for (int i=x;i<y;i++)
#define pb push_back
#define mp make_pair
#define fi first
#define se second

#define dprintf(...) fprintf(stderr,__VA_ARGS__)
using namespace std;

int IN(){
	int c,f,x;
	while (!isdigit(c=getchar())&&c!='-');c=='-'?(f=1,x=0):(f=0,x=c-'0');
	while (isdigit(c=getchar())) x=(x<<1)+(x<<3)+c-'0';return !f?x:-x;
}

typedef long long ll;
typedef double db;
typedef pair<int,int> pii;
typedef vector<int> Vi;

const int N=500+19;
db A[N][N],b[N],c[N];

namespace Simplex{
	const db eps=1e-9;
	db res[N],z;
	int X[N],Y[N];
	int n,m,t;

	void pivot(int x,int y){
		swap(X[y],Y[x]);
		b[x]/=A[x][y];
		For(i,1,m+1) if (i!=y) A[x][i]/=A[x][y];
		A[x][y]=1/A[x][y];
		For(i,1,n+1)
			if (i!=x&&fabs(A[i][y])>eps){
				b[i]-=A[i][y]*b[x];
				For(j,1,m+1) if (j!=y) A[i][j]-=A[i][y]*A[x][j];
				A[i][y]=-A[i][y]*A[x][y];
			}
		z+=c[y]*b[x];
		For(i,1,m+1) if (i!=y) c[i]-=c[y]*A[x][i];
		c[y]=-c[y]*A[x][y];
	}
	void simplex(){
		For(i,1,m+1) X[i]=i;
		For(i,1,n+1) Y[i]=i+m;
		for (;;){
			db mn=-eps;
			int x=0,y=0;
			For(i,1,n+1) if (b[i]<mn) mn=b[i],x=i;
			if (!x) break;
			For(i,1,m+1) if (A[x][i]<-eps) {y=i;break;}
			if (!y){
				puts("Infeasible");
				exit(0);
			}
			pivot(x,y);
		}
		for (;;){
			int x=0,y=0;
			For(i,1,m+1) if (c[i]>eps) {y=i;break;}
			if (!y) break;
			db mn=1e60;
			For(i,1,n+1) if (A[i][y]>eps&&b[i]/A[i][y]<mn) mn=b[i]/A[i][y],x=i;
			if (!x){
				puts("Unbounded");
				exit(0);
			}
			pivot(x,y);
		}
	}
	db Main(){
		simplex();
		return z;
	}
}

struct Edge{
	int x,y,c,f,A,B,C;
} E[N];
Vi I[N],O[N];
int n,m,idx,idy;

int main(){
	n=IN(),m=IN();
	For(i,1,m+1){
		E[i]=(Edge){IN(),IN(),IN(),IN(),0,0,0};
		E[i].A=++idy;
		E[i].B=++idy;
		E[i].C=++idy;
		O[E[i].x].pb(i);
		I[E[i].y].pb(i);
		idx++;
		A[idx][E[i].A]=1;
		b[idx]=E[i].f;
		idx++;
		A[idx][E[i].C]=-1;
		A[idx][E[i].B]=1;
		b[idx]=E[i].c-E[i].f;
		c[E[i].A]=-1;
		c[E[i].B]=-1;
		c[E[i].C]=-1;
	}
	For(x,2,n){
		idx++;
		For(i,0,I[x].size()){
			int t=I[x][i];
			A[idx][E[t].A]--;
			A[idx][E[t].B]++;
			b[idx]-=E[t].f;
		}
		For(i,0,O[x].size()){
			int t=O[x][i];
			A[idx][E[t].A]++;
			A[idx][E[t].B]--;
			b[idx]+=E[t].f;
		}
		idx++;
		For(j,1,idy+1) A[idx][j]=-A[idx-1][j];
		b[idx]=-b[idx-1];
	}
	Simplex::n=idx;
	Simplex::m=idy;
	printf("%d\n",-int(floor(Simplex::Main()+0.5)));
}


#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<bitset>
#include<string>
#include<cstdio>
#include<cctype>
#include<cassert>
#include<cstdlib>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>

#define For(i,x,y) for (int i=x;i<y;i++)
#define pb push_back
#define mp make_pair
#define fi first
#define se second

#define dprintf(...) fprintf(stderr,__VA_ARGS__)
using namespace std;

int IN(){
	int c,f,x;
	while (!isdigit(c=getchar())&&c!='-');c=='-'?(f=1,x=0):(f=0,x=c-'0');
	while (isdigit(c=getchar())) x=(x<<1)+(x<<3)+c-'0';return !f?x:-x;
}

typedef long long ll;
typedef double db;
typedef pair<int,int> pii;
typedef vector<int> Vi;

const int N=500+19;
db A[N][N],b[N],c[N];

namespace Simplex{
	const db eps=1e-7;
	db res[N],z;
	int X[N],Y[N];
	int n,m,t;

	void pivot(int x,int y){
		swap(X[y],Y[x]);
		b[x]/=A[x][y];
		For(i,1,m+1) if (i!=y) A[x][i]/=A[x][y];
		A[x][y]=1/A[x][y];
		For(i,1,n+1)
			if (i!=x&&fabs(A[i][y])>eps){
				b[i]-=A[i][y]*b[x];
				For(j,1,m+1) if (j!=y) A[i][j]-=A[i][y]*A[x][j];
				A[i][y]=-A[i][y]*A[x][y];
			}
		z+=c[y]*b[x];
		For(i,1,m+1) if (i!=y) c[i]-=c[y]*A[x][i];
		c[y]=-c[y]*A[x][y];
	}
	void simplex(){
		For(i,1,m+1) X[i]=i;
		For(i,1,n+1) Y[i]=i+m;
		for (;;){
			db mn=-eps;
			int x=0,y=0;
			For(i,1,n+1) if (b[i]<mn) mn=b[i],x=i;
			if (!x) break;
			For(i,1,m+1) if (A[x][i]<-eps) {y=i;break;}
			if (!y){
				puts("Infeasible");
				exit(0);
			}
			pivot(x,y);
		}
		for (;;){
			int x=0,y=0;
			For(i,1,m+1) if (c[i]>eps) {y=i;break;}
			if (!y) break;
			db mn=1e60;
			For(i,1,n+1) if (A[i][y]>eps&&b[i]/A[i][y]<mn) mn=b[i]/A[i][y],x=i;
			if (!x){
				puts("Unbounded");
				exit(0);
			}
			pivot(x,y);
		}
	}
	db Main(){
		simplex();
		return z;
	}
}

struct Edge{
	int x,y,c,f,A,B,C;
} E[N];
Vi I[N],O[N];
int n,m,idx,idy;

int main(){
	n=IN(),m=IN();
	For(i,1,m+1){
		E[i]=(Edge){IN(),IN(),IN(),IN(),++idy,++idy,++idy};
		O[E[i].x].pb(i);
		I[E[i].y].pb(i);
		idx++;
		A[idx][E[i].A]=1;
		b[idx]=E[i].f;
		idx++;
		A[idx][E[i].C]=-1;
		A[idx][E[i].B]=1;
		b[idx]=E[i].c-E[i].f;
		c[E[i].A]=-1;
		c[E[i].B]=-1;
		c[E[i].C]=-1;
	}
	For(x,2,n){
		idx++;
		For(i,0,I[x].size()){
			int t=I[x][i];
			A[idx][E[t].A]--;
			A[idx][E[t].B]++;
			b[idx]-=E[t].f;
		}
		For(i,0,O[x].size()){
			int t=O[x][i];
			A[idx][E[t].A]++;
			A[idx][E[t].B]--;
			b[idx]+=E[t].f;
		}
		idx++;
		For(j,1,idy+1) A[idx][j]=-A[idx-1][j];
		b[idx]=-b[idx-1];
	}
	Simplex::n=idx;
	Simplex::m=idy;
	printf("%d\n",-int(floor(Simplex::Main()+0.5)));
}


#include <iostream>
#include <queue>

namespace flow {
	const int N = 5000 + 7, M = 50000 + 7;
	const int INF = 1 << 29;

	struct flow {
		int n, st, ed;
		int mincost, maxflow;
		int cur[N], vis[N], dis[N];
		struct edge {
			int to, nex, cap, wei;
		} e[M << 1];
		int fir[N], eid = 1;

		void addedge(int u, int v, int c, int w);
		void addflow(int u, int v, int c, int w);
		int dinic();
		int bfs();
		int dfs(int s, int f);
	};

	void flow::addedge(int u, int v, int c, int w) {
		e[++eid] = (edge) { v, fir[u], c, w }, fir[u] = eid;
	}
	void flow::addflow(int u, int v, int c, int w) {
		addedge(u, v, c, w), addedge(v, u, 0, -w);
	}

	int flow::dinic() {
		maxflow = 0, mincost = 0;
		int f;
		while (bfs()) while (f = dfs(st, INF))
			maxflow += f, mincost += f * dis[st];
		return mincost;
	}
	int flow::bfs() {
		std::fill(dis + 1, dis + n + 1, INF);
		std::fill(vis + 1, vis + n + 1, 0);
		std::copy(fir + 1, fir + n + 1, cur + 1);
		dis[ed] = 0, vis[ed] = 1;
		std::queue <int> q;
		q.push(ed);
		for (int s; q.size(); ) {
			s = q.front(), q.pop();
			for (int i = fir[s]; i; i = e[i].nex)
				if (e[i ^ 1].cap && dis[e[i].to] > dis[s] - e[i].wei) {
					dis[e[i].to] = dis[s] - e[i].wei;
					if (!vis[e[i].to]) vis[e[i].to] = 1, q.push(e[i].to);
				}
			vis[s] = 0;
		}
		return dis[st] < INF;
	}
	int flow::dfs(int s, int f) {
		if (s == ed) return f;
		vis[s] = 1;
		int t, u = 0;
		for (int &i = cur[s]; i; i = e[i].nex) {
			if (vis[e[i].to] || !e[i].cap || dis[s] != dis[e[i].to] + e[i].wei) continue;
			t = dfs(e[i].to, std::min(f - u, e[i].cap));
			e[i].cap -= t, e[i ^ 1].cap += t, u += t;
			if (u == f) break;
		}
		return vis[s] = 0, u;
	}
};

int main() {
	const int N = 100 + 7;

	static int n, m;
	static int h, s;
	static int p[N];
	static flow::flow f;

	scanf("%d%d", &n, &m);
	for (int i = 1, u, v, x, y; i <= m; ++i) {
		scanf("%d%d%d%d", &u, &v, &x, &y);
		if (x >= y)
			f.addflow(v, u, y, 1),
			f.addflow(u, v, x - y, 1),
			f.addflow(u, v, flow::INF, 2);
		else
			h += y - x,
			f.addflow(v, u, y - x, 0),
			f.addflow(v, u, x, 2),
			f.addflow(u, v, flow::INF, 2);
		p[u] -= y, p[v] += y;
	}
	for (int i = 1; i <= n; ++i) {
		if (p[i] > 0) f.addflow(n + 1, i, p[i], 0), s += p[i];
		if (p[i] < 0) f.addflow(i, n + 2, -p[i], 0);
	}
	f.addflow(n, 1, flow::INF, 0);

	f.n = n + 2, f.st = n + 1, f.ed = n + 2;
	f.dinic();
	printf("%d", f.maxflow != s ? -1 : h + f.mincost);

	return 0;
}


#include <iostream>
#include <queue>

namespace flow {
	const int N = 5000 + 7, M = 50000 + 7;
	const int INF = 1 << 29;

	struct flow {
		int n, st, ed;
		int mincost, maxflow;
		int cur[N], vis[N], dis[N];
		struct edge {
			int to, nex, cap, wei;
		} e[M << 1];
		int fir[N], eid = 1;

		void addedge(int u, int v, int c, int w);
		void addflow(int u, int v, int c, int w);
		int dinic();
		int bfs();
		int dfs(int s, int f);
	};

	void flow::addedge(int u, int v, int c, int w) {
		e[++eid] = (edge) { v, fir[u], c, w }, fir[u] = eid;
	}
	void flow::addflow(int u, int v, int c, int w) {
		addedge(u, v, c, w), addedge(v, u, 0, -w);
	}

	int flow::dinic() {
		maxflow = 0, mincost = 0;
		int f;
		while (bfs()) while (f = dfs(st, INF))
			maxflow += f, mincost += f * dis[st];
		return mincost;
	}
	int flow::bfs() {
		std::fill(dis + 1, dis + n + 1, INF);
		std::fill(vis + 1, vis + n + 1, 0);
		std::copy(fir + 1, fir + n + 1, cur + 1);
		dis[ed] = 0, vis[ed] = 1;
		std::queue <int> q;
		q.push(ed);
		for (int s; q.size(); ) {
			s = q.front(), q.pop();
			for (int i = fir[s]; i; i = e[i].nex)
				if (e[i ^ 1].cap && dis[e[i].to] > dis[s] - e[i].wei) {
					dis[e[i].to] = dis[s] - e[i].wei;
					if (!vis[e[i].to]) vis[e[i].to] = 1, q.push(e[i].to);
				}
			vis[s] = 0;
		}
		return dis[st] < INF;
	}
	int flow::dfs(int s, int f) {
		if (s == ed) return f;
		vis[s] = 1;
		int t, u = 0;
		for (int &i = cur[s]; i; i = e[i].nex) {
			if (vis[e[i].to] || !e[i].cap || dis[s] != dis[e[i].to] + e[i].wei) continue;
			t = dfs(e[i].to, std::min(f - u, e[i].cap));
			e[i].cap -= t, e[i ^ 1].cap += t, u += t;
			if (u == f) break;
		}
		return vis[s] = 0, u;
	}
};

int main() {
	const int N = 100 + 7;

	static int n, m;
	static int h, s;
	static int p[N];
	static flow::flow f;

	scanf("%d%d", &n, &m);
	for (int i = 1, u, v, x, y; i <= m; ++i) {
		scanf("%d%d%d%d", &u, &v, &x, &y);
		if (x >= y)
			f.addflow(v, u, y, 1),
			f.addflow(u, v, x - y, 1),
			f.addflow(u, v, flow::INF, 2);
		else
			h += y - x,
			f.addflow(v, u, y - x, 0),
			f.addflow(v, u, x, 1),
			f.addflow(u, v, flow::INF, 2);
		p[u] -= y, p[v] += y;
	}
	for (int i = 1; i <= n; ++i) {
		if (p[i] > 0) f.addflow(n + 1, i, p[i], 0), s += p[i];
		if (p[i] < 0) f.addflow(i, n + 2, -p[i], 0);
	}
	f.addflow(n, 1, flow::INF, 0);

	f.n = n + 2, f.st = n + 1, f.ed = n + 2;
	printf("%d", h + f.dinic());

	return 0;
}


//code in https://github.com/kcm1700/algorithms by kcm1700
#include <functional>
#include <queue>
#include <limits>
#include <vector>
#include <algorithm>

using namespace std;

// tests
// Kaka's matrix travel (POJ)
// https://www.acmicpc.net/problem/8992
// SRM 506 mid
// ACM-ICPC World Finals 2015 C Catering

// precondition: there is no negative cycle.
// usage:
//  MinCostFlow mcf(n);
//  for(each edges) mcf.addEdge(from, to, cost, capacity);
//  mcf.solve(source, sink); // min cost max flow
//  mcf.solve(source, sink, 0); // min cost flow
//  mcf.solve(source, sink, goal_flow); // min cost flow with total_flow >= goal_flow if possible
struct MinCostFlow
{
	typedef long long cap_t;
	typedef long long cost_t;

	bool iszerocap(cap_t cap) { return cap == 0; }

	struct edge {
		int target;
		cost_t cost;
		cap_t residual_capacity;
		cap_t orig_capacity;
		size_t revid;
	};

	int n;
	vector<vector<edge>> graph;
	vector<cost_t> pi;
	bool needNormalize, ranbefore;
	int lastStart;

	MinCostFlow(int n) : graph(n), n(n), pi(n, 0), needNormalize(false), ranbefore(false) {}
	void addEdge(int s, int e, cost_t cost, cap_t cap)
	{
		if (s == e) return;
		edge forward={e, cost, cap, cap, graph[e].size()};
		edge backward={s, -cost, 0, 0, graph[s].size()};
		if (cost < 0 || ranbefore) needNormalize = true;
		graph[s].emplace_back(forward);
		graph[e].emplace_back(backward);
	}
	bool normalize(int s) {
		auto infinite_cost = numeric_limits<cost_t>::max();
		vector<cost_t> dist(n, infinite_cost);
		dist[s] = 0;
		queue<int> q;
		vector<int> v(n), relax_count(n);
		v[s] = 1; q.push(s);
		while(!q.empty()) {
			int cur = q.front();
			v[cur] = 0; q.pop();
			if (++relax_count[cur] >= n) return false;
			for (const auto &e : graph[cur]) {
				if (iszerocap(e.residual_capacity)) continue;
				auto next = e.target;
				auto ncost = dist[cur] + e.cost;
				if (dist[next] > ncost) {
					dist[next] = ncost;
					if (v[next]) continue;
					v[next] = 1; q.push(next);
				}
			}
		}
		for (int i = 0; i < n; i++) pi[i] = dist[i];
		return true;
	}

	pair<cost_t, cap_t> AugmentShortest(int s, int e, cap_t flow_limit) {
		auto infinite_cost = numeric_limits<cost_t>::max();
		auto infinite_flow = numeric_limits<cap_t>::max();
		typedef pair<cost_t, int> pq_t;
		priority_queue<pq_t, vector<pq_t>, greater<pq_t>> pq;
		vector<pair<cost_t, cap_t>> dist(n, make_pair(infinite_cost, 0));
		vector<int> from(n, -1), v(n);

		if (needNormalize || (ranbefore && lastStart != s))
			normalize(s);
		ranbefore = true;
		lastStart = s;

		dist[s] = pair<cost_t, cap_t>(0, infinite_flow);
		pq.emplace(dist[s].first, s);
		while(!pq.empty()) {
			auto cur = pq.top().second; pq.pop();
			if (v[cur]) continue;
			v[cur] = 1;
			if (cur == e) continue;
			for (const auto &e : graph[cur]) {
				auto next = e.target;
				if (v[next]) continue;
				if (iszerocap(e.residual_capacity)) continue;
				auto ncost = dist[cur].first + e.cost - pi[next] + pi[cur];
				auto nflow = min(dist[cur].second, e.residual_capacity);
				if (dist[next].first <= ncost) continue;
				dist[next] = make_pair(ncost, nflow);
				from[next] = e.revid;
				pq.emplace(dist[next].first, next);
			}
		}
		/** augment the shortest path **/
		auto p = e;
		auto pathcost = dist[p].first + pi[p] - pi[s];
		auto flow = dist[p].second;
		if (iszerocap(flow)|| (flow_limit <= 0 && pathcost >= 0)) return pair<cost_t, cap_t>(0, 0);
		if (flow_limit > 0) flow = min(flow, flow_limit);
		/* update potential */
		for (int i = 0; i < n; i++) {
			if (iszerocap(dist[i].second)) continue;
			pi[i] += dist[i].first;
		}
		while (from[p] != -1) {
			auto nedge = from[p];
			auto np = graph[p][nedge].target;
			auto fedge = graph[p][nedge].revid;
			graph[p][nedge].residual_capacity += flow;
			graph[np][fedge].residual_capacity -= flow;
			p = np;
		}
		return make_pair(pathcost * flow, flow);
	}

	pair<cost_t,cap_t> solve(int s, int e, cap_t flow_minimum = numeric_limits<cap_t>::max()) {
		cost_t total_cost = 0;
		cap_t total_flow = 0;
		for(;;) {
			auto res = AugmentShortest(s, e, flow_minimum - total_flow);
			if (res.second <= 0) break;
			total_cost += res.first;
			total_flow += res.second;
		}
		return make_pair(total_cost, total_flow);
	}
};

int n,m;
int eg[110][4];
int fsum[110];
int sans;
int main(){
	int i;
	scanf("%d%d",&n,&m);
	MinCostFlow mcf(n+3);
	sans=0;
	for(i=0;i<m;i++){
		scanf("%d%d%d%d",&eg[i][0],&eg[i][1],&eg[i][2],&eg[i][3]);
		fsum[eg[i][0]]-=eg[i][3];
		fsum[eg[i][1]]+=eg[i][3];
		if(eg[i][2]-eg[i][3]>=0){
			mcf.addEdge(eg[i][0],eg[i][1],1,eg[i][2]-eg[i][3]);
			mcf.addEdge(eg[i][0],eg[i][1],2,999999999);
			mcf.addEdge(eg[i][1],eg[i][0],1,eg[i][3]);
		}
		else{
			sans+=eg[i][3]-eg[i][2];
			mcf.addEdge(eg[i][0],eg[i][1],2,999999999);
			mcf.addEdge(eg[i][1],eg[i][0],0,eg[i][3]-eg[i][2]);
			mcf.addEdge(eg[i][1],eg[i][0],1,eg[i][2]);
		}
	}
	mcf.addEdge(n,1,0,999999999);
	for(i=1;i<=n;i++){
		if(fsum[i]>0){
			mcf.addEdge(n+1,i,0,fsum[i]);
		}
		else{
			mcf.addEdge(i,n+2,0,-fsum[i]);
		}
	}
	printf("%I64d",sans + mcf.solve(n+1,n+2).first);
	return 0;
}


//code in https://github.com/kcm1700/algorithms by kcm1700
#include <functional>
#include <queue>
#include <limits>
#include <vector>
#include <algorithm>

using namespace std;

// tests
// Kaka's matrix travel (POJ)
// https://www.acmicpc.net/problem/8992
// SRM 506 mid
// ACM-ICPC World Finals 2015 C Catering

// precondition: there is no negative cycle.
// usage:
//  MinCostFlow mcf(n);
//  for(each edges) mcf.addEdge(from, to, cost, capacity);
//  mcf.solve(source, sink); // min cost max flow
//  mcf.solve(source, sink, 0); // min cost flow
//  mcf.solve(source, sink, goal_flow); // min cost flow with total_flow >= goal_flow if possible
struct MinCostFlow
{
	typedef long long cap_t;
	typedef long long cost_t;

	bool iszerocap(cap_t cap) { return cap == 0; }

	struct edge {
		int target;
		cost_t cost;
		cap_t residual_capacity;
		cap_t orig_capacity;
		size_t revid;
	};

	int n;
	vector<vector<edge>> graph;
	vector<cost_t> pi;
	bool needNormalize, ranbefore;
	int lastStart;

	MinCostFlow(int n) : graph(n), n(n), pi(n, 0), needNormalize(false), ranbefore(false) {}
	void addEdge(int s, int e, cost_t cost, cap_t cap)
	{
		if (s == e) return;
		edge forward={e, cost, cap, cap, graph[e].size()};
		edge backward={s, -cost, 0, 0, graph[s].size()};
		if (cost < 0 || ranbefore) needNormalize = true;
		graph[s].emplace_back(forward);
		graph[e].emplace_back(backward);
	}
	bool normalize(int s) {
		auto infinite_cost = numeric_limits<cost_t>::max();
		vector<cost_t> dist(n, infinite_cost);
		dist[s] = 0;
		queue<int> q;
		vector<int> v(n), relax_count(n);
		v[s] = 1; q.push(s);
		while(!q.empty()) {
			int cur = q.front();
			v[cur] = 0; q.pop();
			if (++relax_count[cur] >= n) return false;
			for (const auto &e : graph[cur]) {
				if (iszerocap(e.residual_capacity)) continue;
				auto next = e.target;
				auto ncost = dist[cur] + e.cost;
				if (dist[next] > ncost) {
					dist[next] = ncost;
					if (v[next]) continue;
					v[next] = 1; q.push(next);
				}
			}
		}
		for (int i = 0; i < n; i++) pi[i] = dist[i];
		return true;
	}

	pair<cost_t, cap_t> AugmentShortest(int s, int e, cap_t flow_limit) {
		auto infinite_cost = numeric_limits<cost_t>::max();
		auto infinite_flow = numeric_limits<cap_t>::max();
		typedef pair<cost_t, int> pq_t;
		priority_queue<pq_t, vector<pq_t>, greater<pq_t>> pq;
		vector<pair<cost_t, cap_t>> dist(n, make_pair(infinite_cost, 0));
		vector<int> from(n, -1), v(n);

		if (needNormalize || (ranbefore && lastStart != s))
			normalize(s);
		ranbefore = true;
		lastStart = s;

		dist[s] = pair<cost_t, cap_t>(0, infinite_flow);
		pq.emplace(dist[s].first, s);
		while(!pq.empty()) {
			auto cur = pq.top().second; pq.pop();
			if (v[cur]) continue;
			v[cur] = 1;
			if (cur == e) continue;
			for (const auto &e : graph[cur]) {
				auto next = e.target;
				if (v[next]) continue;
				if (iszerocap(e.residual_capacity)) continue;
				auto ncost = dist[cur].first + e.cost - pi[next] + pi[cur];
				auto nflow = min(dist[cur].second, e.residual_capacity);
				if (dist[next].first <= ncost) continue;
				dist[next] = make_pair(ncost, nflow);
				from[next] = e.revid;
				pq.emplace(dist[next].first, next);
			}
		}
		/** augment the shortest path **/
		auto p = e;
		auto pathcost = dist[p].first + pi[p] - pi[s];
		auto flow = dist[p].second;
		if (iszerocap(flow)|| (flow_limit <= 0 && pathcost >= 0)) return pair<cost_t, cap_t>(0, 0);
		if (flow_limit > 0) flow = min(flow, flow_limit);
		/* update potential */
		for (int i = 0; i < n; i++) {
			if (iszerocap(dist[i].second)) continue;
			pi[i] += dist[i].first;
		}
		while (from[p] != -1) {
			auto nedge = from[p];
			auto np = graph[p][nedge].target;
			auto fedge = graph[p][nedge].revid;
			graph[p][nedge].residual_capacity += flow;
			graph[np][fedge].residual_capacity -= flow;
			p = np;
		}
		return make_pair(pathcost * flow, flow);
	}

	pair<cost_t,cap_t> solve(int s, int e, cap_t flow_minimum = numeric_limits<cap_t>::max()) {
		cost_t total_cost = 0;
		cap_t total_flow = 0;
		for(;;) {
			auto res = AugmentShortest(s, e, flow_minimum - total_flow);
			if (res.second <= 0) break;
			total_cost += res.first;
			total_flow += res.second;
		}
		return make_pair(total_cost, total_flow);
	}
};

int n,m;
int eg[110][4];
int fsum[110];
int sans;
int main(){
	int i;
	scanf("%d%d",&n,&m);
	MinCostFlow mcf(n+3);
	sans=0;
	for(i=0;i<m;i++){
		scanf("%d%d%d%d",&eg[i][0],&eg[i][1],&eg[i][2],&eg[i][3]);
		fsum[eg[i][0]]-=eg[i][3];
		fsum[eg[i][1]]+=eg[i][3];
		if(eg[i][2]-eg[i][3]>=0){
			mcf.addEdge(eg[i][0],eg[i][1],1,eg[i][2]-eg[i][3]);
			mcf.addEdge(eg[i][0],eg[i][1],2,999999999);
			mcf.addEdge(eg[i][1],eg[i][0],1,eg[i][3]);
		}
		else{
			sans+=eg[i][3]-eg[i][2];
			mcf.addEdge(eg[i][0],eg[i][1],2,999999999);
			mcf.addEdge(eg[i][0],eg[i][1],0,eg[i][3]-eg[i][2]);
			mcf.addEdge(eg[i][1],eg[i][0],1,eg[i][2]);
		}
	}
	mcf.addEdge(n,1,0,999999999);
	for(i=1;i<=n;i++){
		if(fsum[i]>0){
			mcf.addEdge(n+1,i,0,fsum[i]);
		}
		else{
			mcf.addEdge(i,n+2,0,-fsum[i]);
		}
	}
	printf("%I64d",sans + mcf.solve(n+1,n+2).first);
	return 0;
}