Soldier and Traveling (Codeforces 546E)
Tags: Math, flows

In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.Check if is it possible that after roaming there will be exactly bi soldiers in the i-th city.

Input: First line of input consists of two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 200).Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 100).Next line contains n integers b1, b2, ..., bn (0 ≤ bi ≤ 100).Then m lines follow, each of them consists of two integers p and q (1 ≤ p, q ≤ n, p ≠ q) denoting that there is an undirected road between cities p and q. It is guaranteed that there is at most one road between each pair of cities.

Output: If the conditions can not be met output single word "NO".Otherwise output word "YES" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if i ≠ j) or how many soldiers should stay in city i (if i = j).If there are several possible answers you may output any of them.


Sample Inputs:
4 4
1 2 6 3
3 5 3 1
1 2
2 3
3 4
4 2

2 0
1 2
2 1

Sample Outputs:
YES
1 0 0 0
2 0 0 0
0 5 1 0
0 0 2 1

NO

Solution (Python):
def difstrc(s, n, edges):
    fromnode = {}
    for j in range(s, n):
        list = []
        for i in range(0, len(edges)):
            if edges[i][0] == j:
                list.append([edges[i][1], edges[i][2]])
        fromnode[j] = list
    return fromnode

def RisG(u, v, fromnode, cap):
    j = 0
    while fromnode[u][j][0] != v:
        j = j + 1
    if fromnode[u][j][1] != cap:
        fromnode[u][j][1] = fromnode[u][j][1] - cap
        if len(fromnode[v]) != 0:
            for x in range(0, len(fromnode[v])):
                if fromnode[v][x][0] == u:
                    fromnode[v][x][1] = fromnode[v][x][1] + cap
                    break
                elif x == len(fromnode[v]) - 1:
                    fromnode[v].append([u, cap])
        elif len(fromnode[v]) == 0:
            fromnode[v].append([u, cap])
    else:
        fromnode[u].remove(fromnode[u][j])
        if len(fromnode[v]) != 0:
            for x in range(0, len(fromnode[v])):
                if fromnode[v][x][0] == u:
                    fromnode[v][x][1] = fromnode[v][x][1] + cap
                    break
                elif x == len(fromnode[v]) - 1:
                    fromnode[v].append([u, cap])
        elif len(fromnode[v]) == 0:
            fromnode[v].append([u, cap])
    return fromnode
if __name__ == '__main__':
    nn = []
    while True:
        try:
            nn.append([int(x) for x in input().split()])
        except EOFError:
            break
    n = 2 + 2 * nn[0][0]
    lm = nn[0][1]
    s = 0
    t = nn[0][0] + 1
    edges = []
    a = nn[1]
    a.insert(0, 0)
    b = nn[2]
    b.insert(0, 0)
    sm = 0
    lum = 0
    for i in range(3, len(nn)):
        ele = [nn[i][0] + nn[0][0] + 1, nn[i][1], a[nn[i][0]]]
        edges.append(ele)
        ele = [nn[i][1] + nn[0][0] + 1, nn[i][0], a[nn[i][1]]]
        edges.append(ele)
    for i in range(1, nn[0][0] + 1):
        if a[i] - b[i] > 0:
            ele = [i, i + nn[0][0] + 1, a[i]]
            edges.append(ele)
            sm = sm + a[i] - b[i]
        if a[i] - b[i] < 0:
            ele = [i, i + nn[0][0] + 1, a[i]]
            edges.append(ele)
            lum = lum + b[i] - a[i]
        if a[i] - b[i] == 0:
            ele = [i, i + nn[0][0] + 1, a[i]]
            edges.append(ele)
    for i in range(1, nn[0][0] + 1):
        if a[i] - b[i] > 0:
            ele = [s, i, a[i] - b[i]]
            edges.append(ele)
        if a[i] - b[i] < 0:
            ele = [i, t, b[i] - a[i]]
            edges.append(ele)
    m = len(edges)
    if sm != lum:
        print('NO')
        quit()
    nod = []
    for i in range(s, n):
        nod.append(i)
    lable = {}
    for i in range(1, n):
        lable[i] = 0
    lable[s] = n
    fromnode = difstrc(s, n, edges)
    preflow = {}
    active = [s]
    preflow[s] = 0
    for i in range(len(fromnode[s]) - 1, -1, -1):
        if fromnode[s][i][0] != t:
            active.append(fromnode[s][i][0])
        preflow[fromnode[s][i][0]] = fromnode[s][i][1]
    for i in set(nod) - set(active):
        preflow[i] = 0
    for i in range(len(fromnode[s]) - 1, -1, -1):
        fromnode[fromnode[s][i][0]].append([s, fromnode[s][i][1]])
        fromnode[s].remove(fromnode[s][i])
    results = [[0 for i in range(nn[0][0])] for i in range(nn[0][0])]
    while active != [s]:
        u = active[1]
        vlist = []
        for i in range(0, len(fromnode[u])):
            vlist.append(lable[fromnode[u][i][0]])
        for i in range(0, len(fromnode[u])):
            v = fromnode[u][i][0]
            if lable[u] == lable[v] + 1:
                f = min(preflow[u], fromnode[u][i][1])
                if u > t and v > t:
                    results[u - t - 1][v - t - 1] = results[u - t - 1][v - t - 1] + f
                elif u > t and s < v < t:
                    results[u - t - 1][v - 1] = results[u - t - 1][v - 1] + f
                elif s < u < t and s < v < t:
                    results[u - 1][v - 1] = results[u - 1][v - 1] + f
                elif s < u < t and v > t:
                    results[u - 1][v - t - 1] = results[u - 1][v - t - 1] + f
                preflow[u] = preflow[u] - f
                preflow[v] = preflow[v] + f
                if preflow[v] > 0 and v not in active and (v != t):
                    active.append(v)
                fromnode = RisG(u, v, fromnode, f)
                if preflow[u] == 0:
                    active.remove(u)
                break
            else:
                mv = min(vlist) + 1
                lable[u] = mv
    f = preflow[t]
    for i in range(0, nn[0][0]):
        for j in range(0, nn[0][0]):
            if results[i][j] >= results[j][i]:
                results[i][j] = results[i][j] - results[j][i]
                results[j][i] = 0
            else:
                results[j][i] = results[j][i] - results[i][j]
                results[i][j] = 0
    for i in range(0, nn[0][0]):
        results[i][i] = a[i + 1] - sum(results[i])
    if f != sm:
        print('NO')
    else:
        print('YES')
        for row in results:
            print('%s' % ' '.join(('%s' % i for i in row)))

Solution (Python):
class Dinic:

    class Edge:

        def __init__(self, to, cap, rev):
            self.to = to
            self.cap = cap
            self.rev = rev

        def __repr__(self):
            return '(to: {0} cap: {1} rev: {2})'.format(self.to, self.cap, self.rev)

    def __init__(self, V):
        self.V = V
        self.size = [0 for i in range(V)]
        self.G = [[] for i in range(V)]

    def add_edge(self, _from, to, cap):
        self.G[_from].append(self.Edge(to, cap, self.size[to]))
        self.G[to].append(self.Edge(_from, 0, self.size[_from]))
        self.size[_from] += 1
        self.size[to] += 1

    def bfs(self, s):
        level = [-1 for i in range(self.V)]
        level[s] = 0
        q = []
        q.append(s)
        while q != []:
            v = q.pop(0)
            for u in self.G[v]:
                if u.cap > 0 and level[u.to] < 0:
                    level[u.to] = level[v] + 1
                    q.append(u.to)
        return level

    def dfs(self, v, t, f):
        if v == t:
            return f
        while self.iterator[v] < self.size[v]:
            edge = self.G[v][self.iterator[v]]
            if edge.cap > 0 and self.level[v] < self.level[edge.to]:
                d = self.dfs(edge.to, t, f if f < edge.cap else edge.cap)
                if d > 0:
                    self.G[v][self.iterator[v]].cap -= d
                    self.G[edge.to][edge.rev].cap += d
                    return d
            self.iterator[v] += 1
        return 0

    def max_flow(self, s, t):
        flow = 0
        while True:
            self.level = self.bfs(s)
            if self.level[t] < 0:
                return flow
            self.iterator = [0 for i in range(self.V)]
            while True:
                f = self.dfs(s, t, float('inf'))
                if f == 0:
                    break
                flow += f
(N, M) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ff = Dinic(N * 2 + 2)
S = 1
T = N + 1
for i in range(M):
    (p, q) = map(int, input().split())
    ff.add_edge(p, T + q - 1, 10 ** 9)
    ff.add_edge(q, T + p - 1, 10 ** 9)
for i in range(N):
    ff.add_edge(i + 1, T + i, 10 ** 9)
    ff.add_edge(0, S + i, A[i])
    ff.add_edge(T + i, 2 * N + 1, B[i])
ans = [[0 for i in range(N)] for j in range(N)]
ff.max_flow(0, 2 * N + 1)
for i in range(1, N + 1):
    for v in ff.G[i]:
        if v.to != 0:
            ans[i - 1][v.to - T] = ff.G[v.to][v.rev].cap
if sum(A) != sum(B):
    print('NO')
    quit()
if [sum([ans[i][j] for i in range(N)]) for j in range(N)] == B:
    print('YES')
    for a in ans:
        print(' '.join(map(str, a)))
else:
    print('NO')

Solution (Python):
from sys import stdin
from collections import deque

def bfs(graph, flow, source, dest, previous):
    queue = deque()
    previous.clear()
    previous.extend([None] * len(graph))
    queue.append(source)
    while queue:
        u = queue.popleft()
        for e in graph[u]:
            (v, c, f) = (flow[e][1], flow[e][2], flow[e][3])
            if previous[v] is None and f < c and (v != source):
                previous[v] = e
                queue.append(v)
        if previous[dest] is not None:
            return True
    return False

def fordFulkerson(graph, flow, source, sink):
    total_flow = 0
    previous = []
    while bfs(graph, flow, source, sink, previous):
        e = previous[sink]
        cflow = 1 << 32
        path = []
        while True:
            cflow = min(cflow, flow[e][2] - flow[e][3])
            path.append(e)
            e = previous[flow[e][0]]
            if e is None:
                break
        for e in path:
            flow[e][3] += cflow
            flow[flow[e][4]][3] -= cflow
        total_flow += cflow
    return total_flow

def addEdge(graph, flow, u, v, c):
    flow.append([u, v, c, 0, len(flow) + 1])
    flow.append([v, u, 0, 0, len(flow) - 1])
    graph[u].append(len(flow) - 2)
    graph[v].append(len(flow) - 1)
(n, m) = [int(_) for _ in input().split()]
a = [int(_) for _ in input().split()]
b = [int(_) for _ in input().split()]
graph = [[] for _ in range(n * 2 + 2)]
flow = []
source = n * 2
sink = n * 2 + 1
inf = 1 << 32
for line in stdin.readlines():
    (u, v) = [int(_) - 1 for _ in line.split()]
    addEdge(graph, flow, u, v + n, inf)
    addEdge(graph, flow, v, u + n, inf)
for i in range(n):
    addEdge(graph, flow, i, i + n, a[i])
    addEdge(graph, flow, source, i, a[i])
    addEdge(graph, flow, i + n, sink, b[i])
if sum(a) != sum(b) or fordFulkerson(graph, flow, source, sink) != sum(a):
    print('NO')
else:
    print('YES')
    tr = [[0 for j in range(n)] for i in range(n)]
    edges = [e for e in flow if e[3] > 0 and e[0] < n * 2 and (e[1] < n * 2)]
    for edge in edges:

        def rev_idx(u):
            return u if u < n else u - n
        tr[rev_idx(edge[0])][rev_idx(edge[1])] = edge[3]
    print('\n'.join((' '.join((str(x) for x in row)) for row in tr)))