namespace FeasibleFlow
{
struct edge{int nex,to,flow;}e[MAX<<1];
int head[MAX],down[MAX<<1],cnt=1;
inline void add(int x,int y,int z) {e[++cnt].nex=head[x],head[x]=cnt,e[cnt].to=y,e[cnt].flow=z;}
inline void Add(int x,int y,int l,int r) {add(x,y,r-l),down[cnt]=l,add(y,x,0);}
int N,s,t,S,T,tot,flag;
int maxflow,realflow,d[MAX],pre[MAX];
int in[MAX],out[MAX];
queue<int> q;
inline bool Layer()
{
fill(d+1,d+N+1,0);
while(!q.empty()) q.pop();
d[S]=1,pre[S]=head[S],q.emplace(S);
while(!q.empty())
{
int now=q.front(); q.pop();
for(int i=head[now];i;i=e[i].nex)
{
int to=e[i].to,flow=e[i].flow;
if(!d[to]&&flow)
{
d[to]=d[now]+1,pre[to]=head[to],q.emplace(to);
if(to==T) return 1;
}
}
}
return 0;
}
int Dinic(int now,int flow)
{
if(now==T) return flow;
int rest=flow;
for(int i=pre[now];i;i=e[i].nex)
{
pre[now]=i; int to=e[i].to;
if(d[to]==d[now]+1&&e[i].flow)
{
int k=Dinic(to,min(e[i].flow,rest));
if(!k) d[to]=0;
e[i].flow-=k,e[i^1].flow+=k,rest-=k;
if(!rest) break;
}
}
return flow-rest;
}
inline void Work(int typ)
{
S=N+1,T=N+2,N+=2,flag=1;
for(int i=1;i<=n;++i) if(in[i]>out[i]) Add(S,i,0,in[i]-out[i]),tot+=in[i]-out[i]; else if(in[i]<out[i]) Add(i,T,0,out[i]-in[i]);
Add(t,s,0,INF);
while(Layer()) maxflow+=Dinic(S,INF);
if(tot!=maxflow) flag=0;
if(!flag||!typ) return;
realflow=e[cnt].flow,e[cnt].flow=e[cnt-1].flow=0;
if(typ==1) {S=s,T=t; while(Layer()) realflow+=Dinic(S,INF);}
if(typ==2) {S=t,T=s; while(Layer()) realflow-=Dinic(S,INF);}
}
}