zoj2314

题解:

有上限的网络流

基本模板

代码:

#include<bits/stdc++.h>
using namespace std;
const int N=;
int ne[N],num,n,m,d[N],S,T,a,b,c,low[N],fi[N],zz[N],sl[N],dis[N],q[N];
void jb(int x,int y,int z)
{
ne[num]=fi[x];
fi[x]=num;
zz[num]=y;
sl[num++]=z;
swap(x,y);
z=;
ne[num]=fi[x];
fi[x]=num;
zz[num]=y;
sl[num++]=z;
}
int bfs()
{
memset(dis,0xff,sizeof dis);
dis[]=;
int l=,r=;
q[]=;
while (l<r)
{
int j=q[++l];
for (int i=fi[j];i!=-;i=ne[i])
if (dis[zz[i]]<&&sl[i]>)
{
dis[zz[i]]=dis[j]+;
q[++r]=zz[i];
}
}
if (dis[n]>)return ;
return ;
}
int find(int x,int low)
{
int b=;
if (x==n)return low;
for (int i=fi[x];i!=-;i=ne[i])
if (sl[i]>&&dis[zz[i]]==dis[x]+&&(b=find(zz[i],min(low,sl[i]))))
{
sl[i]-=b;
sl[i^]+=b;
return b;
}
return ;
}
int main()
{
scanf("%d",&T);
while (T--)
{
memset(fi,-,sizeof fi);
num=;
memset(d,,sizeof d);
scanf("%d%d",&n,&m);
for (int i=;i<m;i++)
{
scanf("%d%d%d%d",&a,&b,&low[i],&c);
jb(a+,b+,c-low[i]);
d[a]+=low[i];d[b]-=low[i];
}
int tot=;
for (int i=;i<=n;i++)
{
if (d[i]<)jb(,i+,-d[i]);
else jb(i+,n+,d[i]),tot+=d[i];
}
n+=;
int t,ans=;
while (bfs())
while (t=find(,1e9))ans+=t;
if (tot!=ans)puts("NO");
else
{
puts("YES");
for (int i=;i<m;i++)
printf("%d\n",sl[(i<<)^]+low[i]);
}
puts("");
}
}
上一篇:CAS与OAuth2的区别


下一篇:机器学习基础:(Python)训练集测试集分割与交叉验证