Problem:


Score : 1200 points

Problem Statement

Snuke is playing with red and blue balls, placing them on a two-dimensional plane.

First, he performed N operations to place red balls. In the i-th of these operations, he placed RC_i red balls at coordinates (RX_i,RY_i).
Then, he performed another N operations to place blue balls. In the i-th of these operations, he placed BC_i blue balls at coordinates (BX_i,BY_i).
The total number of red balls placed and the total number of blue balls placed are equal, that is, \sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i. Let this value be S.

Snuke will now form S pairs of red and blue balls so that every ball belongs to exactly one pair.
Let us define the score of a pair of a red ball at coordinates (rx, ry) and a blue ball at coordinates (bx, by) as |rx-bx| + |ry-by|.

Snuke wants to maximize the sum of the scores of the pairs.
Help him by finding the maximum possible sum of the scores of the pairs.

Constraints

1 \leq N \leq 1000

0 \leq RX_i,RY_i,BX_i,BY_i \leq 10^9

1 \leq RC_i,BC_i \leq 10

\sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
RX_1 RY_1 RC_1
RX_2 RY_2 RC_2
\vdots
RX_N RY_N RC_N
BX_1 BY_1 BC_1
BX_2 BY_2 BC_2
\vdots
BX_N BY_N BC_N

Output

Print the maximum possible sum of the scores of the pairs.

Sample Input 1

2
0 0 1
3 2 1
2 2 1
5 0 1

Sample Output 1

8

If we pair the red ball at coordinates (0,0) and the blue ball at coordinates (2,2), the score of this pair is |0-2| + |0-2|=4.
Then, if we pair the red ball at coordinates (3,2) and the blue ball at coordinates (5,0), the score of this pair is |3-5| + |2-0|=4.
Making these two pairs results in the total score of 8, which is the maximum result.

Sample Input 2

3
0 0 1
2 2 1
0 0 2
1 1 1
1 1 1
3 3 2

Sample Output 2

16

Snuke may have performed multiple operations at the same coordinates.

Sample Input 3

10
582463373 690528069 8
621230322 318051944 4
356524296 974059503 6
372751381 111542460 9
392867214 581476334 6
606955458 513028121 5
882201596 791660614 9
250465517 91918758 3
618624774 406956634 6
426294747 736401096 5
974896051 888765942 5
726682138 336960821 3
715144179 82444709 6
599055841 501257806 6
390484433 962747856 4
912334580 219343832 8
570458984 648862300 6
638017635 572157978 10
435958984 585073520 7
445612658 234265014 6

Sample Output 3

45152033546



Sample input:
2
0 0 1
3 2 1
2 2 1
5 0 1


Sample output:
8

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def min_cost_flow(links, s, t, flow):
    remain = flow
    ans = 0

    potentials = [0] * n2  # to adjust negative edge for dijkstra
    predecessors = [None] * n2  # it may be reset in every loop, but not be necessary.

    while remain:
        distances = [INF] * n2
        distances[s] = 0
        q = [(0, s)]  # (cost, v, (p, v_idx_in_p))
        while q:
            cost, v = heappop(q)
            if cost > distances[v]:
                continue

            for i, (u, cap, uc, j) in enumerate(links[v]):
                if cap == 0:
                    continue
                new_cost = cost + uc + potentials[v] - potentials[u]
                if distances[u] <= new_cost:
                    continue
                distances[u] = new_cost
                predecessors[u] = (v, i)
                heappush(q, (new_cost, u))

        # print(potentials)
        # print(predecessors)
        # print(distances)

        if distances[t] == INF:
            return -1

        # potentials = list(map(sum, zip(potentials, distances)))
        for i in range(n2):
            potentials[i] += distances[i]

        # path = [t]
        min_cap = remain
        v = t
        while v != s:
            p, i = predecessors[v]
            l = links[p][i]
            min_cap = min(min_cap, l[1])
            v = p
            # path.append(p)
        # path.reverse()
        # print(path, min_cap)
        v = t
        while v != s:
            p, i = predecessors[v]
            l = links[p][i]
            l[1] -= min_cap
            if v != t:
                links[v][l[3]][1] += min_cap
            v = p
        remain -= min_cap
        ans += min_cap * (REV * 2 - potentials[t])
    return ans


n = int(input())
lines = sys.stdin.readlines()
flow = 0
INF = 10 ** 18
REV = 10 ** 9
n2 = 2 * n + 6
t = 2 * n + 1
links = [[] for _ in range(n2)]  # [[tgt_node, capacity, unit_cost, idx_in_tgt], ]
for ri, line in enumerate(lines[:n], start=1):
    rx, ry, rc = map(int, line.split())
    flow += rc
    links[0].append([ri, rc, 0, 0])
    for k in range(4):
        ki = n2 - 4 + k
        kc = REV - ((k & 1) * 2 - 1) * rx - (((k >> 1) & 1) * 2 - 1) * ry
        links[ri].append([ki, INF, kc, len(links[ki])])
        links[ki].append([ri, 0, -kc, len(links[ri]) - 1])

for bi, line in enumerate(lines[n:], start=n + 1):
    bx, by, bc = map(int, line.split())
    links[bi].append([t, bc, 0, 0])
    for k in range(4):
        ki = n2 - 4 + k
        kc = REV - ((k & 1) * -2 + 1) * bx - (((k >> 1) & 1) * -2 + 1) * by
        links[ki].append([bi, INF, kc, len(links[bi])])
        links[bi].append([ki, 0, -kc, len(links[ki]) - 1])

print(min_cost_flow(links, 0, t, flow))

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def min_cost_flow(links, s, t, flow):
    remain = flow
    ans = 0

    potentials = [0] * n2  # to adjust negative edge for dijkstra
    predecessors = [None] * n2  # it may be reset in every loop, but not be necessary.

    while remain:
        distances = [INF] * n2
        distances[s] = 0
        q = [(0, s)]  # (cost, v, (p, v_idx_in_p))
        while q:
            cost, v = heappop(q)
            if cost > distances[v]:
                continue

            for i, (u, cap, uc, j) in enumerate(links[v]):
                if cap == 0:
                    continue
                new_cost = cost + uc + potentials[v] - potentials[u]
                if distances[u] <= new_cost:
                    continue
                distances[u] = new_cost
                predecessors[u] = (v, i)
                heappush(q, (new_cost, u))

        # print(potentials)
        # print(predecessors)
        # print(distances)

        if distances[t] == INF:
            return -1

        potentials = list(map(sum, zip(potentials, distances)))

        # path = [t]
        min_cap = remain
        v = t
        while v != s:
            p, i = predecessors[v]
            l = links[p][i]
            min_cap = min(min_cap, l[1])
            v = p
            # path.append(p)
        # path.reverse()
        # print(path, min_cap)
        v = t
        while v != s:
            p, i = predecessors[v]
            l = links[p][i]
            l[1] -= min_cap
            if v != t:
                links[v][l[3]][1] += min_cap
            v = p
        remain -= min_cap
        ans += min_cap * (REV * 2 - potentials[t])
    return ans


n = int(input())
lines = sys.stdin.readlines()
flow = 0
INF = 10 ** 18
REV = 10 ** 9
n2 = 2 * n + 6
t = 2 * n + 1
links = [[] for _ in range(n2)]  # [[tgt_node, capacity, unit_cost, idx_in_tgt], ]
for ri, line in enumerate(lines[:n], start=1):
    rx, ry, rc = map(int, line.split())
    flow += rc
    links[0].append([ri, rc, 0, 0])
    for k in range(4):
        ki = n2 - 4 + k
        kc = REV - ((k & 1) * 2 - 1) * rx - (((k >> 1) & 1) * 2 - 1) * ry
        links[ri].append([ki, INF, kc, len(links[ki])])
        links[ki].append([ri, 0, -kc, len(links[ri]) - 1])

for bi, line in enumerate(lines[n:], start=n + 1):
    bx, by, bc = map(int, line.split())
    links[bi].append([t, bc, 0, 0])
    for k in range(4):
        ki = n2 - 4 + k
        kc = REV - ((k & 1) * -2 + 1) * bx - (((k >> 1) & 1) * -2 + 1) * by
        links[ki].append([bi, INF, kc, len(links[bi])])
        links[bi].append([ki, 0, -kc, len(links[ki]) - 1])

print(min_cost_flow(links, 0, t, flow))

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def min_cost_flow(links, s, t, flow):
    remain = flow
    ans = 0
    INF = 10 ** 18

    potentials = [0] * (2 * n + 2)  # to adjust negative edge for dijkstra
    predecessors = [None] * (2 * n + 2)  # it may be reset in every loop, but not be necessary.

    while remain:
        distances = [INF] * (2 * n + 2)
        distances[s] = 0
        q = [(0, s)]  # (cost, v, (p, v_idx_in_p))
        while q:
            cost, v = heappop(q)
            if cost > distances[v]:
                continue

            for i, (u, cap, uc, j) in enumerate(links[v]):
                if cap == 0:
                    continue
                new_cost = cost + uc + potentials[v] - potentials[u]
                if distances[u] <= new_cost:
                    continue
                distances[u] = new_cost
                predecessors[u] = (v, i)
                heappush(q, (new_cost, u))

        # print(potentials)
        # print(predecessors)
        # print(distances)

        if distances[t] == INF:
            return -1

        potentials = list(map(sum, zip(potentials, distances)))

        # path = [t]
        min_cap = remain
        v = t
        while v != s:
            p, i = predecessors[v]
            l = links[p][i]
            min_cap = min(min_cap, l[1])
            v = p
            # path.append(p)
        # path.reverse()
        # print(path, min_cap)
        v = t
        while v != s:
            p, i = predecessors[v]
            l = links[p][i]
            l[1] -= min_cap
            if v != t:
                links[v][l[3]][1] += min_cap
            v = p
        remain -= min_cap
        ans += min_cap * (REV - potentials[t])
    return ans


n = int(input())
lines = sys.stdin.readlines()
m = 0
REV = 2 * 10 ** 9
red_cells = []
links = [[] for _ in range(2 * n + 2)]  # [[tgt_node, capacity, unit_cost, idx_in_tgt], ]
t = 2 * n + 1
for i, line in enumerate(lines[:n], start=1):
    x, y, c = map(int, line.split())
    m += c
    red_cells.append((x, y, c))
    links[0].append([i, c, 0, 0])

for bi, line in enumerate(lines[n:], start=n + 1):
    bx, by, bc = map(int, line.split())
    for ri, (rx, ry, rc) in enumerate(red_cells, start=1):
        cap = min(rc, bc)
        cost = REV - (abs(rx - bx) + abs(by - ry))
        links[ri].append([bi, cap, cost, len(links[bi])])
        links[bi].append([ri, 0, -cost, len(links[ri]) - 1])
    links[bi].append([t, bc, 0, 0])

print(min_cost_flow(links, 0, t, m))

Submission status: Accepted

Solution code:
from networkx import*
N = int(input())
G = MultiDiGraph()
for i in range(N):
    x, y, c = map(int, input().split())
    G.add_node(i, demand = -c)
    G.add_weighted_edges_from([(i, -1, x + y), (i, -2, x - y), (i, -3, -x + y), (i, -4, -x - y)], capacity = c)
for i in range(N, N * 2):
    x, y, c = map(int, input().split())
    G.add_node(i, demand = c)
    G.add_weighted_edges_from([(-1, i, -x - y), (-2, i, -x + y), (-3, i, x - y), (-4, i, x + y)], capacity = c)

print(-min_cost_flow_cost(G))

Submission status: Accepted

Solution code:
from networkx import*
N = int(input())
G = MultiDiGraph()
for i in range(N):
    x, y, c = map(int, input().split())
    G.add_node(i, demand = -c)
    G.add_weighted_edges_from([(i, -1, x + y)], capacity = c)
    G.add_weighted_edges_from([(i, -2, x - y)], capacity = c)
    G.add_weighted_edges_from([(i, -3, -x + y)], capacity = c)
    G.add_weighted_edges_from([(i, -4, -x - y)], capacity = c)
for i in range(N):
    x, y, c = map(int, input().split())
    G.add_node(N + i, demand = c)
    G.add_weighted_edges_from([(-1, N + i, -x - y)], capacity = c)
    G.add_weighted_edges_from([(-2, N + i, -x + y)], capacity = c)
    G.add_weighted_edges_from([(-3, N + i, x - y)], capacity = c)
    G.add_weighted_edges_from([(-4, N + i, x + y)], capacity = c)

print(-min_cost_flow_cost(G))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from heapq import heappop, heappush

N = int(readline())
m = map(int,read().split())
data = list(zip(m,m,m))
R = data[:N]
B = data[N:]

class MinCostFlow:
    """
    最小費用流。負辺がないと仮定して、BellmanFordを省略している。
    """
    def __init__(self, N, source, sink):
        self.N = N
        self.G = [[] for _ in range(N)]
        self.source = source
        self.sink = sink
        
    def add_edge(self, fr, to, cap, cost):
        n1 = len(self.G[fr])
        n2 = len(self.G[to])
        self.G[fr].append([to, cap, cost, n2])
        self.G[to].append([fr, 0, -cost, n1])

    def MinCost(self, flow, negative_edge = False):
        if negative_edge:
            raise ValueError
        N = self.N; G = self.G; source = self.source; sink = self.sink
        INF = 10 ** 18
        prev_v = [0] * N; prev_e = [0] * N # 経路復元用
        H = [0] * N # potential
        mincost=0
        while flow:
            dist=[INF] * N
            dist[source]=0
            q = [source]
            mask = (1 << 20) - 1
            while q:
                x = heappop(q)
                dv = (x >> 20); v = x & mask
                if dist[v] < dv:
                    continue
                if v == sink:
                    break
                for i,(w,cap,cost,rev) in enumerate(G[v]):
                    dw = dist[v] + cost + H[v] - H[w]
                    if (not cap) or (dist[w] <= dw):
                        continue
                    dist[w] = dw
                    prev_v[w] = v; prev_e[w] = i
                    heappush(q, (dw << 20) + w)
            #if dist[sink] == INF:
            #    raise Exception('No Flow Exists')
            # ポテンシャルの更新
            for v,d in enumerate(dist):
                H[v] += d
            # 流せる量を取得する
            d = flow; v = sink
            while v != source:
                pv = prev_v[v]; pe = prev_e[v]
                cap = G[pv][pe][1]
                if d > cap:
                    d = cap
                v = pv
            # 流す
            mincost += d * H[sink]
            flow -= d
            v = sink
            while v != source:
                pv = prev_v[v]; pe = prev_e[v]
                G[pv][pe][1] -= d
                rev = G[pv][pe][3]
                G[v][rev][1] += d
                v = pv
        return mincost

source = N+N; sink = N+N+1
V1 = N+N+2; V2 = N+N+3; V3 = N+N+4; V4 = N+N+5

G = MinCostFlow(N+N+6, source = source, sink = sink)
base = 10 ** 9 * 2 # 各辺に上乗せしておく -> 最後に引く
INF = 10 ** 18

flow = 0

for i,(x,y,c) in enumerate(R):
    flow += c
    G.add_edge(fr=source, to=i, cap=c, cost=0)
    G.add_edge(i,V1,INF,base-x-y)
    G.add_edge(i,V2,INF,base-x+y)
    G.add_edge(i,V3,INF,base+x-y)
    G.add_edge(i,V4,INF,base+x+y)

for i,(x,y,c) in enumerate(B,N):
    G.add_edge(fr=i, to=sink, cap=c, cost=0)
    G.add_edge(V1,i,INF,base+x+y)
    G.add_edge(V2,i,INF,base+x-y)
    G.add_edge(V3,i,INF,base-x+y)
    G.add_edge(V4,i,INF,base-x-y)

cost = G.MinCost(flow)

answer = base * (2 * flow) - cost
print(answer)

Submission status: Accepted

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    from collections import deque
    inf=10**12

    class MinCostFlow:
        def __init__(self,n):
            self.n=n
            self.edges=[[] for i in range(n)]
        def add_edge(self,fr,to,cap,cost):
            self.edges[fr].append([to,cap,cost,len(self.edges[to])])
            self.edges[to].append([fr,0,-cost,len(self.edges[fr])-1])
        def MinCost(self,source,sink,flow):
            n=self.n; E=self.edges
            mincost=0
            prev_v=[0]*n; prev_e=[0]*n
            while flow:
                dist=[inf]*n
                dist[source]=0
                q=deque([source])
                Flag=[False]*n
                Flag[source]=True
                while q:
                    v=q.popleft()
                    if not Flag[v]:
                        continue
                    Flag[v]=False
                    for i,(to,cap,cost,_) in enumerate(E[v]):
                        if cap>0 and dist[to]>dist[v]+cost:
                            dist[to]=dist[v]+cost
                            prev_v[to],prev_e[to]=v,i
                            q.append(to)
                            Flag[to]=True
                f,v=flow,sink
                while v!=source:
                    f=min(f,E[prev_v[v]][prev_e[v]][1])
                    v=prev_v[v]
                flow-=f
                mincost+=f*dist[sink]
                v=sink
                while v!=source:
                    E[prev_v[v]][prev_e[v]][1]-=f
                    rev=E[prev_v[v]][prev_e[v]][3]
                    E[v][rev][1]+=f
                    v=prev_v[v]
            return mincost

    n=int(input())
    flow=MinCostFlow(2*n+6)
    s=0
    for i in range(n):
        rx,ry,rc=map(int,input().split())
        s+=rc
        flow.add_edge(0,i+1,rc,0)
        flow.add_edge(i+1,n+1,inf,-rx-ry)
        flow.add_edge(i+1,n+2,inf,rx-ry)
        flow.add_edge(i+1,n+3,inf,-rx+ry)
        flow.add_edge(i+1,n+4,inf,rx+ry)
    for i in range(n):
        bx,by,bc=map(int,input().split())
        flow.add_edge(n+5+i,2*n+5,bc,0)
        flow.add_edge(n+1,n+5+i,inf,bx+by)
        flow.add_edge(n+2,n+5+i,inf,-bx+by)
        flow.add_edge(n+3,n+5+i,inf,bx-by)
        flow.add_edge(n+4,n+5+i,inf,-bx-by)
    print(-(flow.MinCost(0,2*n+5,s)))

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    from collections import deque
    inf=10**12

    class MinCostFlow:
        def __init__(self,n):
            self.n=n
            self.edges=[[] for i in range(n)]
        def add_edge(self,fr,to,cap,cost):
            self.edges[fr].append([to,cap,cost,len(self.edges[to])])
            self.edges[to].append([fr,0,-cost,len(self.edges[fr])-1])
        def MinCost(self,source,sink,flow):
            n=self.n; E=self.edges
            mincost=0
            prev_v=[0]*n; prev_e=[0]*n
            while flow:
                dist=[inf]*n
                dist[source]=0
                q=deque([source])
                Flag=[False] *n
                Flag[source]=True
                while q:
                    v=q.popleft()
                    if not Flag[v] :
                        continue
                    Flag[v]=False
                    for i,(w,cap,cost,_) in enumerate(E[v]):
                        if cap>0 and dist[w]>dist[v]+cost:
                            dist[w]=dist[v]+cost
                            prev_v[w],prev_e[w]=v,i
                            q.append(w)
                            Flag[w]=True
                d,v=flow,sink
                while v!=source:
                    d=min(d,E[prev_v[v]][prev_e[v]][1])
                    v=prev_v[v]
                flow-=d
                mincost+=d*dist[sink]
                v=sink
                while v!=source:
                    e=E[prev_v[v]][prev_e[v]]
                    e[1]-=d
                    E[v][e[3]][1]+=d
                    v=prev_v[v]
            return mincost

    n=int(input())
    flow=MinCostFlow(2*n+6)
    s=0
    for i in range(n):
        rx,ry,rc=map(int,input().split())
        s+=rc
        flow.add_edge(0,i+1,rc,0)
        flow.add_edge(i+1,n+1,inf,-rx-ry)
        flow.add_edge(i+1,n+2,inf,rx-ry)
        flow.add_edge(i+1,n+3,inf,-rx+ry)
        flow.add_edge(i+1,n+4,inf,rx+ry)
    for i in range(n):
        bx,by,bc=map(int,input().split())
        flow.add_edge(n+5+i,2*n+5,bc,0)
        flow.add_edge(n+1,n+5+i,inf,bx+by)
        flow.add_edge(n+2,n+5+i,inf,-bx+by)
        flow.add_edge(n+3,n+5+i,inf,bx-by)
        flow.add_edge(n+4,n+5+i,inf,-bx-by)
    print(-(flow.MinCost(0,2*n+5,s)))

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = sys.stdin.readline

N = int(input())
N_ = 2 * N + 6
N1, N2, N3, N4, N5 = range(N + 1, N + 6)
G = [[] for i in range(2 * N + 6)]
INF = 10 ** 12

def add_edge(fr, to, cap, cost) :
        G[fr].append([to, cap, cost, len(G[to])])
        G[to].append([fr, 0, -cost, len(G[fr]) - 1])

def flow(s, t, f) :
    ret = 0
    pre_v = [0] * N_
    pre_e = [0] * N_

    while f :
        dist = [INF] * N_
        dist[s] = 0
        que = deque([s])
        updated = [False] * N_
        updated[s] = True

        while que :
            v = que.popleft()
            if not updated[v] :
                continue

            updated[v] = False

            for i, (w, cap, cost, _) in enumerate(G[v]) :
                if cap > 0 and dist[w] > dist[v] + cost:
                    dist[w] = dist[v] + cost
                    pre_v[w], pre_e[w] = v, i
                    que.append(w)
                    updated[w] = True

        d, v = f, t
        while v != s :
            d = min(d, G[pre_v[v]][pre_e[v]][1])
            v = pre_v[v]

        f -= d
        ret += d * dist[t]

        v = t
        while v != s :
            e = G[pre_v[v]][pre_e[v]]
            e[1] -= d
            G[v][e[3]][1] += d
            v = pre_v[v]
    
    return ret

S = 0
for i in range(1, N + 1) :
    Rx, Ry, Rc = map(int, input().split())

    add_edge(0, i, Rc, 0)

    add_edge(i, N1, INF, -Rx - Ry)
    add_edge(i, N2, INF, Rx - Ry)
    add_edge(i, N3, INF, -Rx + Ry)
    add_edge(i, N4, INF, Rx + Ry)
    S += Rc

for i in range(N5, N_ - 1) :
    Bx, By, Bc = map(int, input().split())
    add_edge(N1, i, INF, Bx + By)
    add_edge(N2, i, INF, -Bx + By)
    add_edge(N3, i, INF, Bx - By)
    add_edge(N4, i, INF, -Bx - By)

    add_edge(i, N_ - 1, Bc, 0)

print(-flow(0, N_ - 1, S))

Submission status: Accepted

Solution code:
import sys
from collections import deque


def min_cost_flow(links, links_from, s, t, flow, n2):
    remain = flow
    result = 0
    INF = 10 ** 12
    predecessors = [0] * n2  # link_id

    while remain:
        # print(remain)
        distances = [INF] * n2
        updated = [False] * n2
        distances[s] = 0
        updated[s] = True
        q = deque([s])
        while q:
            v = q.popleft()
            vc = distances[v]
            updated[v] = False

            for li in links_from[v]:
                _, u, cap, cost = links[li]
                if cap == 0:
                    continue
                new_cost = vc + cost
                if new_cost >= distances[u]:
                    continue
                distances[u] = new_cost
                predecessors[u] = li
                if not updated[u]:
                    updated[u] = True
                    q.append(u)

        min_cap = remain
        v = t
        while v != s:
            li = predecessors[v]
            l = links[li]
            min_cap = min(min_cap, l[2])
            v = l[0]
        v = t
        while v != s:
            li = predecessors[v]
            l = links[li]
            l[2] -= min_cap
            links[li ^ 1][2] += min_cap
            v = l[0]
        remain -= min_cap
        result -= min_cap * distances[t]
    return result


n = int(input())
lines = sys.stdin.readlines()
n2 = 2 * n + 6
s, t = 0, 2 * n + 1
k1, k2, k3, k4 = range(n2 - 4, n2)
balls = 0
links_from = [[] for _ in range(n2)]
links = []  # [[src, tgt, capacity, unit_cost], ]


def add_link(s, t, cap, cost):
    i = len(links)
    links.append([s, t, cap, cost])
    links.append([t, s, 0, -cost])
    links_from[s].append(i)
    links_from[t].append(i + 1)


for i in range(n):
    ri = i + 1
    rx, ry, rc = map(int, lines[i].split())
    balls += rc
    add_link(s, ri, rc, 0)
    add_link(ri, k1, rc, rx + ry)
    add_link(ri, k2, rc, -rx + ry)
    add_link(ri, k3, rc, rx - ry)
    add_link(ri, k4, rc, -rx - ry)

for i in range(n, 2 * n):
    bi = i + 1
    bx, by, bc = map(int, lines[i].split())
    add_link(bi, t, bc, 0)
    add_link(k1, bi, bc, -bx - by)
    add_link(k2, bi, bc, bx - by)
    add_link(k3, bi, bc, -bx + by)
    add_link(k4, bi, bc, bx + by)

print(min_cost_flow(links, links_from, s, t, balls, n2))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from heapq import heappush, heappop
def min_cost_flow_dijkstra(E, s, t, f):
    INF = 1 << 100
    NN = N
    LN = NN.bit_length()
    G = [[] for _ in range(NN)]
    for a, b, cap, c in E:
        G[a].append([b, cap, c, len(G[b])])
        G[b].append([a, 0, -c, len(G[a])-1])
    prevv = [-1] * NN
    preve = [-1] * NN
    res = 0
    while f > 0:
        h = [0] * NN
        dist = [INF] * NN
        dist[s] = 0
        Q = []
        heappush(Q, s)
        while len(Q):
            x = heappop(Q)
            d, v = (x>>LN), x % (1<<LN)
            if dist[v] < d: continue
            for i, (w, _cap, c, r) in enumerate(G[v]):
                if _cap > 0 and dist[w] > dist[v] + c + h[v] - h[w]:
                    dist[w] = dist[v] + c + h[v] - h[w]
                    prevv[w] = v
                    preve[w] = i
                    heappush(Q, (dist[w] << LN) + w)
        if dist[t] == INF:
            return -1
        for v in range(N):
            h[v] += dist[v]
        
        d = f
        v = t
        while v != s:
            d = min(d, G[prevv[v]][preve[v]][1])
            v = prevv[v]
        f -= d
        res += d * dist[t]
        v = t
        while v != s:
            G[prevv[v]][preve[v]][1] -= d
            G[v][G[prevv[v]][preve[v]][3]][1] += d
            v = prevv[v]
    return res

E = []
N = int(input())
su = 0
inf = 1 << 31
for i in range(N):
    x, y, cnt = map(int, input().split())
    E.append((2*N+4, i, cnt, 0))
    E.append((i, 2*N, cnt, x + y + inf))
    E.append((i, 2*N+1, cnt, x - y + inf))
    E.append((i, 2*N+2, cnt, - x + y + inf))
    E.append((i, 2*N+3, cnt, - x - y + inf))
    su += cnt

for i in range(N):
    x, y, cnt = map(int, input().split())
    E.append((i+N, 2*N+5, cnt, 0))
    E.append((2*N, i+N, cnt, - x - y + inf))
    E.append((2*N+1, i+N, cnt, - x + y + inf))
    E.append((2*N+2, i+N, cnt, x - y + inf))
    E.append((2*N+3, i+N, cnt, x + y + inf))

print(su * inf * 2 - min_cost_flow_dijkstra(E, 2*N+4, 2*N+5, su))

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

N = int(readline())
S = np.frombuffer(b'-'+readline().rstrip(),'S1')
Q = int(readline())
query = map(int,read().split())

isD = S == b'D'
isM = S == b'M'
isC = S == b'C'

cumD = isD.cumsum(dtype=np.int64)
cumM = isM.cumsum(dtype=np.int64)

def F(K):
    x = cumD.copy(); x[K:] -= cumD[:-K]
    x *= isM
    x[K+1:] -= isD[1:-K] * (cumM[K:-1] - cumM[:-K-1])
    return (x.cumsum() * isC).sum()

print('\n'.join(str(F(K)) for K in query))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from heapq import *
def min_cost_flow_dijkstra(E, s, t, f):
    NN = 2 * N + 6
    G = [[] for _ in range(NN)]
    for a, b, cap, c in E:
        G[a].append([b, cap, c, len(G[b])])
        G[b].append([a, 0, -c, len(G[a])-1])
    prevv = [-1] * NN
    preve = [-1] * NN
    h = [0] * NN
    res = 0
    while f > 0:
        dist = [1<<100] * NN
        dist[s] = 0
        q = []
        heappush(q, s)
        while h:
            di, v = q.pop()
            if dist[v] < di: continue
            for i, (b, _cap, c, r) in enumerate(G[v]):
                if _cap > 0 and dist[b] > dist[v] + c + h[v] - h[b]:
                    dist[b] = dist[v] + c + h[v] - h[b]
                    prevv[b] = v
                    preve[b] = i
                    heappush(q, (dist[b], b))
        
        
        if dist[t] == 1<<100:
            return -1
        for v in range(NN):
            h[v] += dist[v]
        
        d = f
        v = t
        while v != s:
            d = min(d, G[prevv[v]][preve[v]][1])
            v = prevv[v]
        f -= d
        res += d * h[t]
        v = t
        while v != s:
            G[prevv[v]][preve[v]][1] -= d
            G[v][G[prevv[v]][preve[v]][3]][1] += d
            v = prevv[v]
    return res

E = []
N = int(input())
su = 0
INF = 1 << 31
for i in range(N):
    x, y, cnt = map(int, input().split())
    E.append((2*N+4, i, cnt, 0))
    E.append((i, 2*N, cnt, x + y + INF))
    E.append((i, 2*N+1, cnt, x - y + INF))
    E.append((i, 2*N+2, cnt, - x + y + INF))
    E.append((i, 2*N+3, cnt, - x - y + INF))
    su += cnt

for i in range(N):
    x, y, cnt = map(int, input().split())
    E.append((i+N, 2*N+5, cnt, 0))
    E.append((2*N, i+N, cnt, - x - y + INF))
    E.append((2*N+1, i+N, cnt, - x + y + INF))
    E.append((2*N+2, i+N, cnt, x - y + INF))
    E.append((2*N+3, i+N, cnt, x + y + INF))

print(su * INF * 2 - min_cost_flow(E, 2*N+4, 2*N+5, su))

Submission status: Runtime Error

Solution code:
from heapq import *
def min_cost_flow_dijkstra(E, s, t, f):
    NN = 2 * N + 6
    G = [[] for _ in range(NN)]
    for a, b, cap, c in E:
        G[a].append([b, cap, c, len(G[b])])
        G[b].append([a, 0, -c, len(G[a])-1])
    prevv = [-1] * NN
    preve = [-1] * NN
    h = [0] * NN
    res = 0
    while f > 0:
        dist = [1<<100] * NN
        dist[s] = 0
        q = []
        heappush(q, s)
        while h:
            di, v = q.pop()
            if dist[v] < di: continue
            for i, (b, _cap, c, r) in enumerate(G[v]):
                if _cap > 0 and dist[b] > dist[v] + c + h[v] - h[b]:
                    dist[b] = dist[v] + c + h[v] - h[b]
                    prevv[b] = v
                    preve[b] = i
                    heappush(q, (dist[b], b))
        
        
        if dist[t] == 1<<100:
            return -1
        for v in range(NN):
            h[v] += dist[v]
        
        d = f
        v = t
        while v != s:
            d = min(d, G[prevv[v]][preve[v]][1])
            v = prevv[v]
        f -= d
        res += d * h[t]
        v = t
        while v != s:
            G[prevv[v]][preve[v]][1] -= d
            G[v][G[prevv[v]][preve[v]][3]][1] += d
            v = prevv[v]
    return res

E = []
N = int(input())
su = 0
INF = 1 << 31
for i in range(N):
    x, y, cnt = map(int, input().split())
    E.append((2*N+4, i, cnt, 0))
    E.append((i, 2*N, cnt, x + y + INF))
    E.append((i, 2*N+1, cnt, x - y + INF))
    E.append((i, 2*N+2, cnt, - x + y + INF))
    E.append((i, 2*N+3, cnt, - x - y + INF))
    su += cnt

for i in range(N):
    x, y, cnt = map(int, input().split())
    E.append((i+N, 2*N+5, cnt, 0))
    E.append((2*N, i+N, cnt, - x - y + INF))
    E.append((2*N+1, i+N, cnt, - x + y + INF))
    E.append((2*N+2, i+N, cnt, x - y + INF))
    E.append((2*N+3, i+N, cnt, x + y + INF))

print(su * INF * 2 - min_cost_flow(E, 2*N+4, 2*N+5, su))