LOJ 115 无源汇有上下界可行流
思路
模板题
首先把下界去掉(连边upper-lower
然后记录每个点至少要流出的和流入的流量(下界
然后流入大于流出的连向tt,流出大于流入的连向ss(补流
然后跑最大流,如果sum=flow,就代表加上的边满流,有答案,否则没有
代码
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#define int long long
using namespace std;
const int MAXN = 20100;
const int INF = 0x3f3f3f3f;
struct Edge{
int u,v,cap,flow;
};
vector<int> G[MAXN];
vector<Edge> edges;
int n,m,d[MAXN],sumx,lower[MAXN],ss,tt,vis[MAXN],dep[MAXN],cur[MAXN],id[50000];
void addedge(int u,int v,int cap){
edges.push_back((Edge){u,v,cap,0});
edges.push_back((Edge){v,u,0,0});
int cnt=edges.size();
G[u].push_back(cnt-2);
G[v].push_back(cnt-1);
}
void addedge(int u,int v,int cap,int lower){
addedge(u,v,cap-lower);
d[u]+=lower;
d[v]-=lower;
}
int dfs(int x,int a){
if(x==tt||a==0)
return a;
int flow=0,f;
for(int &i=cur[x];i<G[x].size();i++){
Edge &e = edges[G[x][i]];
if(dep[e.v]==dep[x]+1&&(f=dfs(e.v,min(e.cap-e.flow,a)))>0){
flow+=f;
e.flow+=f;
edges[G[x][i]^1].flow-=f;
a-=f;
if(!a)
break;
}
}
return flow;
}
queue<int> q;
bool bfs(void){
memset(vis,0,sizeof(vis));
dep[ss]=0;
q.push(ss);
vis[ss]=1;
while(!q.empty()){
int x=q.front();
q.pop();
for(int i=0;i<G[x].size();i++){
Edge &e = edges[G[x][i]];
if((!vis[e.v])&&e.cap>e.flow){
dep[e.v]=dep[x]+1;
vis[e.v]=true;
q.push(e.v);
}
}
}
return vis[tt];
}
int dinic(void){
int flow=0;
while(bfs()){
memset(cur,0,sizeof(cur));
flow+=dfs(ss,INF);
}
return flow;
}
signed main(){
// freopen("1.in","r",stdin);
// freopen("1.out","w",stdout);
scanf("%lld %lld",&n,&m);
for(int i=1;i<=m;i++){
int a,b,c;
scanf("%lld %lld %lld %lld",&a,&b,&lower[i],&c);
addedge(a,b,c,lower[i]);
id[i]=edges.size()-2;
}
ss=MAXN-2;
tt=MAXN-3;
for(int i=1;i<=n;i++){
if(d[i]>0){
addedge(i,tt,d[i]);
sumx+=d[i];
}
else{
addedge(ss,i,-d[i]);
}
}
int max_flow=dinic();
// printf("sumx=%lld maxflow=%lld\n",sumx,max_flow);
if(sumx==max_flow){
printf("YES\n");
for(int i=1;i<=m;i++)
printf("%lld\n",lower[i]+edges[id[i]].flow);
}
else{
printf("NO\n");
}
return 0;
}