题目大意:给出M条管道,每条管道都有相应的下界和上界
现在问每条管道之间形成一个环,管道之间流量的最大值是多少
解题思路:两点之间的有向边的容量就是边的上界-下界
然后添加一个超级源点,连线那些流入的值大于流出的值的点,容量为流入值-流出值
再添加一个超级汇点,连线那些流入值小于流出值的点,容量为流出值-流入值
接着跑最大流,如果满流,表示可行
要求每条边的流量,只要找出每条边的流量,再加上每条边的下界即可
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAXNODE = 210;
const int MAXEDGE = 100010;
typedef int Type;
const Type INF = 0x3f3f3f3f;
struct Edge{
int u,v,next,id;
Type cap,flow;
Edge() {}
Edge(int u,int v,Type cap,Type flow,int next,int id) : u(u),v(v),cap(cap),flow(flow),next(next),id(id){}
};
struct Dinic{
int n,m,s,t;
Edge edges[MAXEDGE];
int head[MAXNODE];
int cur[MAXNODE];
bool vis[MAXNODE];
Type d[MAXNODE];
vector<int> cut;
void init(int n) {
this->n = n;
memset(head,-1,sizeof(head));
m = 0;
}
void AddEdge(int u,int id) {
edges[m] = Edge(u,cap,0,head[u],id);
head[u] = m++;
edges[m] = Edge(v,u,head[v],id);
head[v] = m++;
}
bool BFS() {
memset(vis,sizeof(vis));
queue<int> Q;
Q.push(s);
d[s] = 0;
vis[s] = 1;
while (!Q.empty()) {
int u = Q.front(); Q.pop();
for (int i = head[u]; ~i; i = edges[i].next) {
Edge &e = edges[i];
if (!vis[e.v] && e.cap > e.flow) {
vis[e.v] = true;
d[e.v] = d[u] + 1;
Q.push(e.v);
}
}
}
return vis[t];
}
Type DFS(int u,Type a) {
if (u == t || a == 0) return a;
Type flow = 0,f;
for (int &i = cur[u]; i != -1; i = edges[i].next) {
Edge &e = edges[i];
if (d[u] + 1 == d[e.v] && (f = DFS(e.v,min(a,e.cap - e.flow))) > 0) {
e.flow += f;
edges[i ^ 1].flow -= f;
flow += f;
a -= f;
if (a == 0) break;
}
}
return flow;
}
Type Maxflow(int s,int t) {
this->s = s; this->t = t;
Type flow = 0;
while (BFS()) {
for (int i = 0; i < n; i++)
cur[i] = head[i];
flow += DFS(s,INF);
}
return flow;
}
void Mincut() {
cut.clear();
for (int i = 0; i < m; i += 2) {
if (vis[edges[i].u] && !vis[edges[i].v])
cut.push_back(i);
}
}
bool judge() {
for (int i = head[s]; ~i; i = edges[i].next)
if (edges[i].cap - edges[i].flow != 0)
return false;
return true;
}
}dinic;
int n,m;
int d[MAXNODE],ans[MAXEDGE];
void solve() {
memset(d,sizeof(d));
int source = n + 1,sink = n + 2;
dinic.init(sink + 1);
int u,up,down;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d%d",&u,&v,&down,&up);
dinic.AddEdge(u,up - down,i);
ans[i] = down;
d[u] -= down;
d[v] += down;
}
int tot = dinic.m;
for (int i = 1; i <= n; i++) {
if (d[i] > 0) dinic.AddEdge(source,i,d[i],0);
if (d[i] < 0) dinic.AddEdge(i,sink,-d[i],0);
}
dinic.Maxflow(source,sink);
if (!dinic.judge()) printf("NO\n");
else {
for (int i = 0; i < tot; i += 2)
ans[dinic.edges[i].id] += dinic.edges[i].flow;
printf("YES\n");
for (int i = 1; i <= m; i++)
printf("%d\n",ans[i]);
}
}
int main() {
while (~scanf("%d%d",&n,&m)) solve();
return 0;
}