<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

194. Reactor Cooling
time limit per test: 0.5 sec.
memory limit per test: 65536 KB
input: standard
output: standard



The terrorist group leaded by a well known international terrorist Ben Bladen is buliding a nuclear reactor to produce plutonium for the nuclear bomb they are planning to create. Being the wicked computer genius of this group, you are responsible for developing the cooling system for the reactor.

The cooling system of the reactor consists of the number of pipes that special cooling liquid flows by. Pipes are connected at special points, called nodes, each pipe has the starting node and the end point. The liquid must flow by the pipe from its start point to its end point and not in the opposite direction.

Let the nodes be numbered from 1 to N. The cooling system must be designed so that the liquid is circulating by the pipes and the amount of the liquid coming to each node (in the unit of time) is equal to the amount of liquid leaving the node. That is, if we designate the amount of liquid going by the pipe from i-th node to j-th as fij, (put fij = 0 if there is no pipe from node i to node j), for each i the following condition must hold:


sum(j=1..N, fij) = sum(j=1..N, fji)


Each pipe has some finite capacity, therefore for each i and j connected by the pipe must be fij ≤ cij where cij is the capacity of the pipe. To provide sufficient cooling, the amount of the liquid flowing by the pipe going from i-th to j-th nodes must be at least lij, thus it must be fij ≥ lij.

Given cij and lij for all pipes, find the amount fij, satisfying the conditions specified above.

Input

The first line of the input file contains the number N (1 ≤ N ≤ 200) - the number of nodes and and M — the number of pipes. The following M lines contain four integer number each - i, j, lij and cij each. There is at most one pipe connecting any two nodes and 0 ≤ lij ≤ cij ≤ 105 for all pipes. No pipe connects a node to itself. If there is a pipe from i-th node to j-th, there is no pipe from j-th node to i-th.

Output

On the first line of the output file print YES if there is the way to carry out reactor cooling and NO if there is none. In the first case M integers must follow, k-th number being the amount of liquid flowing by the k-th pipe. Pipes are numbered as they are given in the input file.

Sample test(s)

Input
Test #1

4 6
1 2 1 2
2 3 1 2
3 4 1 2
4 1 1 2
1 3 1 2
4 2 1 2

Test #2

4 6
1 2 1 3
2 3 1 3
3 4 1 3
4 1 1 3
1 3 1 3
4 2 1 3

Output
Test #1

NO

Test #2

YES
1
2
3
2
1
1

Author:	Andrew Stankevich
Resource:	Petrozavodsk Winter Trainings 2003
Date:	2003-02-06

<|response|>
1. Abridged problem statement
You are given a directed graph with N nodes and M edges. Each edge k goes from uₖ to vₖ, has a lower bound lₖ and an upper bound cₖ on the flow. Find a circulation fₖ on every edge such that for each edge lₖ ≤ fₖ ≤ cₖ and at every node, total inflow equals total outflow. If such a circulation exists, output YES and one valid assignment f₁…fₘ; otherwise output NO.

2. Key observations
- A flow with lower bounds can be reduced to a standard max‐flow problem by “shifting” each edge’s flow by its lower bound.
- Once you send lₖ units by default on edge k, you only have to decide the extra flow f′ₖ = fₖ − lₖ within capacity cₖ−lₖ.
- The mandatory lower‐bound flows create imbalances at the nodes: some nodes have a net surplus, others a net demand. To fix them, we introduce a super‐source S and super‐sink T, connect S to each node with net demand, and each node with net surplus to T.
- If the max‐flow from S to T exactly matches the total demand, a feasible circulation exists; otherwise it does not.
- Recover the true flow on each original edge as fₖ = f′ₖ + lₖ.

3. Full solution approach
Step 1. Read N, M and the list of edges (u, v, l, c).
Step 2. Initialize an array balance[1..N] to zero.
Step 3. Build a flow network with N+2 nodes (0…N−1 for original, S=N, T=N+1).
Step 4. For each original edge k from u to v with lower bound l and capacity c:
  • Add an edge u→v with capacity (c−l) to the flow network, storing the edge index k for later.
  • Do balance[u] -= l and balance[v] += l.
Step 5. Compute the total demand D = sum of all positive balance[i].
Step 6. For i = 0…N−1:
  • If balance[i] > 0, add edge S→i with capacity = balance[i].
  • If balance[i] < 0, add edge i→T with capacity = −balance[i].
Step 7. Run a max‐flow from S to T. Let F be the achieved flow.
Step 8. If F < D, output NO and stop. Otherwise output YES.
Step 9. Recover each original flow: for edge k, let f′ be the flow on the reduced‐cap edge; then f = f′ + l. Print these in the order of input.

Overall complexity is dominated by one max‐flow on up to N+2 nodes and O(N+M) edges, which is efficient for N≤200, M up to O(N²).

4. C++ implementation
```cpp
#include <bits/stdc++.h>
// #include <coding_library/graph/maxflow.hpp>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for(auto& x: a) {
        in >> x;
    }
    return in;
};

template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for(auto x: a) {
        out << x << ' ';
    }
    return out;
};

template<class T>
class MaxFlow {
  private:
    const static T INF = numeric_limits<T>::max();

    struct Edge {
        T flow, cap;
        int idx, rev, to;
        Edge(int _to, int _rev, T _flow, T _cap, int _idx)
            : to(_to), rev(_rev), flow(_flow), cap(_cap), idx(_idx) {}
    };

    vector<int> dist, po;
    int n;

    bool bfs(int s, int t) {
        fill(dist.begin(), dist.end(), -1);
        fill(po.begin(), po.end(), 0);

        queue<int> q;
        q.push(s);
        dist[s] = 0;

        while(!q.empty()) {
            int u = q.front();
            q.pop();

            for(Edge e: adj[u]) {
                if(dist[e.to] == -1 && e.flow < e.cap) {
                    dist[e.to] = dist[u] + 1;
                    q.push(e.to);
                }
            }
        }
        return dist[t] != -1;
    }

    T dfs(int u, int t, T fl = INF) {
        if(u == t) {
            return fl;
        }

        for(; po[u] < (int)adj[u].size(); po[u]++) {
            auto& e = adj[u][po[u]];
            if(dist[e.to] == dist[u] + 1 && e.flow < e.cap) {
                T f = dfs(e.to, t, min(fl, e.cap - e.flow));
                e.flow += f;
                adj[e.to][e.rev].flow -= f;
                if(f > 0) {
                    return f;
                }
            }
        }

        return 0;
    }

  public:
    MaxFlow(int n = 0) { init(n); }

    vector<vector<Edge>> adj;

    void init(int _n) {
        n = _n;
        adj.assign(n + 1, {});
        dist.resize(n + 1);
        po.resize(n + 1);
    }

    void add_edge(int u, int v, T w, int idx = -1) {
        adj[u].push_back(Edge(v, adj[v].size(), 0, w, idx));
        adj[v].push_back(Edge(u, adj[u].size() - 1, 0, 0, -1));
    }

    T flow(int s, int t) {
        assert(s != t);

        T ret = 0, to_add;
        while(bfs(s, t)) {
            while((to_add = dfs(s, t))) {
                ret += to_add;
            }
        }

        return ret;
    }
};

int n, m;
vector<tuple<int, int, int, int>> edges;

void read() {
    cin >> n >> m;
    for(int i = 0; i < m; i++) {
        int u, v, cap, lb;
        cin >> u >> v >> lb >> cap;
        edges.emplace_back(u - 1, v - 1, lb, cap);
    }
}

void solve() {
    // - This is a feasible circulation with lower bounds. Each pipe (u, v) with
    //   bounds [lb, cap] is replaced by an edge of capacity cap - lb, and the
    //   mandatory lb flow is accounted for by node excesses: lb leaves u and
    //   enters v.
    //
    // - Add a super source s and super sink t. For each node, its net forced
    //   excess sum_flow[i] is connected to s (if positive, capacity sum_flow[i])
    //   or to t (if negative). A feasible circulation exists iff the max flow
    //   from s to t saturates all source edges, i.e. equals delta = total
    //   positive excess.
    //
    // - The flow on each original pipe is then lb plus the flow pushed on its
    //   reduced edge, recovered through the stored edge index.

    int s = n, t = n + 1;
    MaxFlow<int> mf(n + 2);

    vector<int> sum_flow(n);
    for(int i = 0; i < m; i++) {
        auto [u, v, lb, cap] = edges[i];
        mf.add_edge(u, v, cap - lb, i);
        sum_flow[u] -= lb;
        sum_flow[v] += lb;
    }

    int delta = 0;
    for(int i = 0; i < n; i++) {
        if(sum_flow[i] > 0) {
            delta += sum_flow[i];
            mf.add_edge(s, i, sum_flow[i]);
        } else if(sum_flow[i] < 0) {
            mf.add_edge(i, t, -sum_flow[i]);
        }
    }

    int flow = mf.flow(s, t);
    if(flow != delta) {
        cout << "NO\n";
        return;
    }

    cout << "YES\n";
    vector<int> ans(m);
    for(int i = 0; i < n; i++) {
        for(auto e: mf.adj[i]) {
            if(e.idx != -1) {
                ans[e.idx] = e.flow + get<2>(edges[e.idx]);
            }
        }
    }
    for(int x: ans) {
        cout << x << '\n';
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T = 1;
    // cin >> T;
    for(int test = 1; test <= T; test++) {
        read();
        // cout << "Case #" << test << ": ";
        solve();
    }

    return 0;
}
```

5. Python implementation with detailed comments
```python
import sys
from collections import deque

class Dinic:
    class Edge:
        __slots__ = ('to','rev','cap','flow')
        def __init__(self, to, rev, cap):
            self.to = to
            self.rev = rev
            self.cap = cap
            self.flow = 0

    def __init__(self, n):
        self.n = n
        self.adj = [[] for _ in range(n)]
        self.level = [0]*n
        self.ptr = [0]*n

    def add_edge(self, u, v, cap):
        # forward edge
        self.adj[u].append(Dinic.Edge(v, len(self.adj[v]), cap))
        # reverse edge
        self.adj[v].append(Dinic.Edge(u, len(self.adj[u])-1, 0))

    def bfs(self, S, T):
        for i in range(self.n):
            self.level[i] = -1
        self.level[S] = 0
        dq = deque([S])
        while dq:
            u = dq.popleft()
            for e in self.adj[u]:
                if self.level[e.to] < 0 and e.flow < e.cap:
                    self.level[e.to] = self.level[u] + 1
                    dq.append(e.to)
        return self.level[T] >= 0

    def dfs(self, u, T, pushed):
        if u == T or pushed == 0:
            return pushed
        for cid in range(self.ptr[u], len(self.adj[u])):
            e = self.adj[u][cid]
            if self.level[e.to] == self.level[u] + 1 and e.flow < e.cap:
                tr = self.dfs(e.to, T, min(pushed, e.cap - e.flow))
                if tr > 0:
                    e.flow += tr
                    self.adj[e.to][e.rev].flow -= tr
                    return tr
            self.ptr[u] += 1
        return 0

    def max_flow(self, S, T):
        flow = 0
        INF = 10**18
        while self.bfs(S, T):
            self.ptr = [0]*self.n
            while True:
                pushed = self.dfs(S, T, INF)
                if pushed == 0:
                    break
                flow += pushed
        return flow

def main():
    input = sys.stdin.readline
    N, M = map(int, input().split())
    edges = []
    balance = [0]*N

    # read edges and adjust balances
    for _ in range(M):
        u, v, l, c = map(int, input().split())
        u -= 1; v -= 1
        edges.append((u, v, l, c))
        balance[u] -= l
        balance[v] += l

    S, T = N, N+1
    dinic = Dinic(N+2)

    # add reduced‐capacity edges
    for (u, v, l, c) in edges:
        dinic.add_edge(u, v, c - l)

    # connect super‐source/sink according to balance
    total_demand = 0
    for i in range(N):
        if balance[i] > 0:
            dinic.add_edge(S, i, balance[i])
            total_demand += balance[i]
        elif balance[i] < 0:
            dinic.add_edge(i, T, -balance[i])

    # run max‐flow
    flow = dinic.max_flow(S, T)
    if flow < total_demand:
        print("NO")
        return

    # feasible circulation found
    print("YES")
    # recover original flows in input order
    # we scan the adjacency of each u looking for the v
    ptr = [0]*N
    for (u, v, l, c) in edges:
        # find the edge in adj[u] going to v
        while True:
            e = dinic.adj[u][ptr[u]]
            ptr[u] += 1
            # the original reduced cap was c−l
            if e.to == v and e.cap == c - l:
                # e.flow = f' = f − l
                print(e.flow + l)
                break

if __name__ == "__main__":
    main()
```
