#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<stack>
#include<queue>
#include<cstring>
#define PAU putchar(' ')
#define ENT putchar('\n')
#define MSE(a,b) memset(a,b,sizeof(a))
#define REN(x) for(ted*e=fch[x];e;e=e->nxt)
#define TIL(x) for(int i=1;i<=x;i++)
using namespace std;
const int maxn=+,maxm=+,inf=1e9;
struct zkw{
struct ted{int x,y,w,c;ted*nxt,*re;}adj[maxm],*fch[maxn],*ms;
int n,S,T,d[maxn],cost,ans;bool inq[maxn],vis[maxn];
void init(int n){this->n=n;ms=adj;MSE(vis,false);MSE(inq,false);return;}
void add(int x,int y,int w,int c){
*ms=(ted){x,y,w,c,fch[x],ms+};fch[x]=ms++;
*ms=(ted){y,x,,-c,fch[y],ms-};fch[y]=ms++;
return;
}
bool bfs(){
TIL(n)d[i]=inf;queue<int>Q;Q.push(T);d[T]=;
while(!Q.empty()){
int x=Q.front();Q.pop();inq[x]=false;REN(x){
int v=e->y;if(e->re->w&&d[v]>d[x]+e->re->c){
d[v]=d[x]+e->re->c;if(!inq[v])inq[v]=true,Q.push(v);
}
}
}for(ted*e=adj;e!=ms;e++)e->c+=d[e->y]-d[e->x];cost+=d[S];return d[S]!=inf;
}
int dfs(int x,int aug){
if(x==T||!aug)return(ans+=aug*cost,aug);int flow=,k;vis[x]=true;REN(x){
int v=e->y;if(e->w&&!e->c&&!vis[v]&&(k=dfs(v,min(aug,e->w)))){
e->w-=k;e->re->w+=k;flow+=k;aug-=k;if(!aug)break;
}
}return flow;
}
int mcmf(int S,int T){
this->S=S;this->T=T;while(bfs())do MSE(vis,false);while(dfs(S,inf));return ans;
}
}sol;
inline int read(){
int x=,sig=;char ch=getchar();
for(;!isdigit(ch);ch=getchar())if(ch=='-')sig=;
for(;isdigit(ch);ch=getchar())x=*x+ch-'';
return sig?x:-x;
}
inline void write(int x){
if(x==){putchar('');return;}if(x<)putchar('-'),x=-x;
int len=,buf[];while(x)buf[len++]=x%,x/=;
for(int i=len-;i>=;i--)putchar(buf[i]+'');return;
}
int n,m;
int main(){
n=read();m=read();sol.init(n);int x,y,w;
TIL(m)x=read(),y=read(),w=read(),sol.add(x,y,w,read());write(sol.mcmf(,n));
return ;
}
05-11 11:16