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 heappush, heappop

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
    H = [0] * N_
    pre_v = [0] * N_
    pre_e = [0] * N_

    while f :
        dist = [INF] * N_
        dist[s] = 0
        que = [(0, s)]

        while que :
            c, v = heappop(que)
            if dist[v] < c :
                continue
            for i, (w, cap, cost, _) in enumerate(G[v]) :
                if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w] :
                    dist[w] = r = dist[v] + cost + H[v] - H[w]
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, (r, w))

        for i in range(N_) :
            H[i] += dist[i]

        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 * H[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(N) :
    Rx, Ry, Rc = map(int, input().split())

    add_edge(0, i + 1, Rc, 0)

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappush, heappop

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 = [(0, s)]

        while que :
            c, v = heappop(que)
            if dist[v] < c :
                continue
            for i, (w, cap, cost, _) in enumerate(G[v]) :
                if cap > 0 and dist[w] > dist[v] + cost:
                    dist[w] = r = dist[v] + cost
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, (r, w))

        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(N) :
    Rx, Ry, Rc = map(int, input().split())

    add_edge(0, i + 1, Rc, 0)

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappush, heappop

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)]

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 = [float('inf')] * N_
        dist[s] = 0
        que = [(0, s)]

        while que :
            c, v = heappop(que)
            if dist[v] < c :
                continue
            for i, (w, cap, cost, _) in enumerate(G[v]) :
                if cap > 0 and dist[w] > dist[v] + cost:
                    dist[w] = r = dist[v] + cost
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, (r, w))

        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(N) :
    Rx, Ry, Rc = map(int, input().split())

    add_edge(0, i + 1, Rc, 0)

    add_edge(i + 1, N1, float('inf'), -(Rx + Ry))
    add_edge(i + 1, N2, float('inf'), -(-Rx + Ry))
    add_edge(i + 1, N3, float('inf'), -(Rx - Ry))
    add_edge(i + 1, N4, float('inf'), -(-Rx - Ry))
    S += Rc

for i in range(N) :
    Bx, By, Bc = map(int, input().split())
    add_edge(N1, i + N5, float('inf'), -(-Bx - By))
    add_edge(N2, i + N5, float('inf'), -(Bx - By))
    add_edge(N3, i + N5, float('inf'), -(-Bx + By))
    add_edge(N4, i + N5, float('inf'), -(Bx + By))

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappush, heappop

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)]

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 = [float('inf')] * N_
        dist[s] = 0
        update = True

        while update :
            update = False
            for v in range(N_) :
                if dist[v] == float('inf') :
                    continue
                
                for i, (to, cap, cost, _) in enumerate(G[v]) :
                    if cap > 0 and dist[to] > dist[v] + cost :
                        dist[to] = dist[v] + cost
                        pre_v[to] = v
                        pre_e[to] = i
                        update = 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(N) :
    Rx, Ry, Rc = map(int, input().split())

    add_edge(0, i + 1, Rc, 0)

    add_edge(i + 1, N1, float('inf'), -(Rx + Ry))
    add_edge(i + 1, N2, float('inf'), -(-Rx + Ry))
    add_edge(i + 1, N3, float('inf'), -(Rx - Ry))
    add_edge(i + 1, N4, float('inf'), -(-Rx - Ry))
    S += Rc

for i in range(N) :
    Bx, By, Bc = map(int, input().split())
    add_edge(N1, i + N5, float('inf'), -(-Bx - By))
    add_edge(N2, i + N5, float('inf'), -(Bx - By))
    add_edge(N3, i + N5, float('inf'), -(-Bx + By))
    add_edge(N4, i + N5, float('inf'), -(Bx + By))

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappush, heappop

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)]

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
    H = [0] * N_
    pre_v = [0] * N_
    pre_e = [0] * N_

    while f :
        dist = [float('inf')] * N_
        dist[s] = 0
        que = [(0, s)]

        while que :
            c, v = heappop(que)
            if dist[v] < c :
                continue
            for i, (w, cap, cost, _) in enumerate(G[v]) :
                if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w] :
                    dist[w] = r = dist[v] + cost + H[v] - H[w]
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, (r, w))
        
        # if dist[t] == float('inf') :
        #     return -1

        for i in range(N_) :
            H[i] += dist[i]

        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 * H[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(N) :
    Rx, Ry, Rc = map(int, input().split())

    add_edge(0, i + 1, Rc, 0)

    add_edge(i + 1, N1, float('inf'), -(Rx + Ry))
    add_edge(i + 1, N2, float('inf'), -(-Rx + Ry))
    add_edge(i + 1, N3, float('inf'), -(Rx - Ry))
    add_edge(i + 1, N4, float('inf'), -(-Rx - Ry))
    S += Rc

for i in range(N) :
    Bx, By, Bc = map(int, input().split())
    add_edge(N1, i + N5, float('inf'), -(-Bx - By))
    add_edge(N2, i + N5, float('inf'), -(Bx - By))
    add_edge(N3, i + N5, float('inf'), -(-Bx + By))
    add_edge(N4, i + N5, float('inf'), -(Bx + By))

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappush, heappop

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)]

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
    H = [0] * N_
    pre_v = [0] * N_
    pre_e = [0] * N_

    while f :
        dist = [float('inf')] * N_
        dist[s] = 0
        que = [(0, s)]

        while que :
            c, v = heappop(que)
            if dist[v] < c :
                continue
            for i, (w, cap, cost, _) in enumerate(G[v]) :
                if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w] :
                    dist[w] = r = dist[v] + cost + H[v] - H[w]
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, (r, w))
        
        if dist[t] == float('inf') :
            return -1

        for i in range(N_) :
            H[i] += dist[i]

        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 * H[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(N) :
    Rx, Ry, Rc = map(int, input().split())

    add_edge(0, i + 1, Rc, 0)

    add_edge(i + 1, N1, float('inf'), -(Rx + Ry))
    add_edge(i + 1, N2, float('inf'), -(-Rx + Ry))
    add_edge(i + 1, N3, float('inf'), -(Rx - Ry))
    add_edge(i + 1, N4, float('inf'), -(-Rx - Ry))
    S += Rc

for i in range(N) :
    Bx, By, Bc = map(int, input().split())
    add_edge(N1, i + N5, float('inf'), -(-Bx - By))
    add_edge(N2, i + N5, float('inf'), -(Bx - By))
    add_edge(N3, i + N5, float('inf'), -(-Bx + By))
    add_edge(N4, i + N5, float('inf'), -(Bx + By))

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappush, heappop

input = sys.stdin.readline

N = int(input())
R = [[int(i) for i in input().split()] for _ in range(N)]
B = [[int(i) for i in input().split()] for _ in range(N)]

class MinCostFlow :
    def __init__(self, N) :
        self.N = N
        self.G = [[] for i in range(N)]

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

    def flow(self, s, t, f) :
        N, G = self.N, self.G

        ret = 0
        H = [0] * N
        pre_v = [0] * N
        pre_e = [0] * N

        while f :
            dist = [float('inf')] * N
            dist[s] = 0
            que = [(0, s)]

            while que :
                c, v = heappop(que)
                if dist[v] < c :
                    continue
                for i, (w, cap, cost, _) in enumerate(G[v]) :
                    if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w] :
                        dist[w] = r = dist[v] + cost + H[v] - H[w]
                        pre_v[w], pre_e[w] = v, i
                        heappush(que, (r, w))
            
            if dist[t] == float('inf') :
                return -1

            for i in range(N) :
                H[i] += dist[i]

            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 * H[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

MCF = MinCostFlow(2 * N + 6)
f = 0
for i in range(N) :
    Rx, Ry, Rc = R[i]
    Bx, By, Bc = B[i]

    MCF.add_edge(0, i + 1, Rc, 0)

    MCF.add_edge(i + 1, N + 1, float('inf'), -(Rx + Ry))
    MCF.add_edge(i + 1, N + 2, float('inf'), -(-Rx + Ry))
    MCF.add_edge(i + 1, N + 3, float('inf'), -(Rx - Ry))
    MCF.add_edge(i + 1, N + 4, float('inf'), -(-Rx - Ry))

    MCF.add_edge(N + 1, i + N + 5, float('inf'), -(-Bx - By))
    MCF.add_edge(N + 2, i + N + 5, float('inf'), -(Bx - By))
    MCF.add_edge(N + 3, i + N + 5, float('inf'), -(-Bx + By))
    MCF.add_edge(N + 4, i + N + 5, float('inf'), -(Bx + By))

    MCF.add_edge(i + N + 5, 2 * N + 5, Bc, 0)

    f += Rc

print(-MCF.flow(0, 2 * N + 5, f))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop

N = int(input())
R = [[int(i) for i in input().split()] for _ in range(N)]
B = [[int(i) for i in input().split()] for _ in range(N)]

class MinCostFlow :
    def __init__(self, N) :
        self.N = N
        self.G = [[] for i in range(N)]

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

    def flow(self, s, t, f) :
        N, G = self.N, self.G

        ret = 0
        H = [0] * N
        pre_v = [0] * N
        pre_e = [0] * N

        while f :
            dist = [float('inf')] * N
            dist[s] = 0
            que = [(0, s)]

            while que :
                c, v = heappop(que)
                if dist[v] < c :
                    continue
                for i, (w, cap, cost, _) in enumerate(G[v]) :
                    if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w] :
                        dist[w] = r = dist[v] + cost + H[v] - H[w]
                        pre_v[w], pre_e[w] = v, i
                        heappush(que, (r, w))
            
            if dist[t] == float('inf') :
                return -1

            for i in range(N) :
                H[i] += dist[i]

            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 * H[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

MCF = MinCostFlow(2 * N + 6)
f = 0
for i in range(N) :
    Rx, Ry, Rc = R[i]
    Bx, By, Bc = B[i]

    MCF.add_edge(0, i + 1, Rc, 0)

    MCF.add_edge(i + 1, N + 1, float('inf'), -(Rx + Ry))
    MCF.add_edge(i + 1, N + 2, float('inf'), -(-Rx + Ry))
    MCF.add_edge(i + 1, N + 3, float('inf'), -(Rx - Ry))
    MCF.add_edge(i + 1, N + 4, float('inf'), -(-Rx - Ry))

    MCF.add_edge(N + 1, i + N + 5, float('inf'), -(-Bx - By))
    MCF.add_edge(N + 2, i + N + 5, float('inf'), -(Bx - By))
    MCF.add_edge(N + 3, i + N + 5, float('inf'), -(-Bx + By))
    MCF.add_edge(N + 4, i + N + 5, float('inf'), -(Bx + By))

    MCF.add_edge(i + N + 5, 2 * N + 5, Bc, 0)

    f += Rc

print(-MCF.flow(0, 2 * N + 5, f))

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


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

    potentials = [0] * n2  # to adjust negative edge for dijkstra
    predecessors_v = [0] * n2
    predecessors_i = [0] * n2

    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_v[u] = v
                predecessors_i[u] = i
                heappush(q, (new_cost, u))

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

        for i in range(n2):
            potentials[i] += distances[i]

        min_cap = remain
        v = t
        forward_links = []
        backward_links = []
        while v != s:
            p = predecessors_v[v]
            i = predecessors_i[v]
            l = links[p][i]
            forward_links.append(l)
            if v != t:
                backward_links.append(links[v][l[3]])
            min_cap = min(min_cap, l[1])
            v = p
        for l in forward_links:
            l[1] -= min_cap
        for l in backward_links:
            l[1] += min_cap
        remain -= min_cap
        ans += min_cap * (REV * 2 - potentials[t])
    return ans


n = int(input())
lines = sys.stdin.readlines()
INF = 10 ** 18
REV = 10 ** 9
n2 = 2 * n + 6
t = 2 * n + 1
red_balls = []
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())
    red_balls.append(rc)
    ki = n2 - 4
    kc = REV - (rx + ry)
    links[ri].append([ki, INF, kc, len(links[ki])])
    links[ki].append([ri, 0, -kc, len(links[ri]) - 1])
    ki = n2 - 3
    kc = REV - (-rx + ry)
    links[ri].append([ki, INF, kc, len(links[ki])])
    links[ki].append([ri, 0, -kc, len(links[ri]) - 1])
    ki = n2 - 2
    kc = REV - (rx - ry)
    links[ri].append([ki, INF, kc, len(links[ki])])
    links[ki].append([ri, 0, -kc, len(links[ri]) - 1])
    ki = n2 - 1
    kc = REV - (-rx - 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])
    ki = n2 - 4
    kc = REV - (-bx - by)
    links[ki].append([bi, INF, kc, len(links[bi])])
    links[bi].append([ki, 0, -kc, len(links[ki]) - 1])
    ki = n2 - 3
    kc = REV - (bx - by)
    links[ki].append([bi, INF, kc, len(links[bi])])
    links[bi].append([ki, 0, -kc, len(links[ki]) - 1])
    ki = n2 - 2
    kc = REV - (-bx + by)
    links[ki].append([bi, INF, kc, len(links[bi])])
    links[bi].append([ki, 0, -kc, len(links[ki]) - 1])
    ki = n2 - 1
    kc = REV - (bx + by)
    links[ki].append([bi, INF, kc, len(links[bi])])
    links[bi].append([ki, 0, -kc, len(links[ki]) - 1])

ans = 0
for i, flow in enumerate(red_balls, start=1):
    ans += min_cost_flow(links, i, t, flow, n2, INF, REV)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def min_cost_flow(links, s, t, flow, n, n2, INF, REV):
    remain = flow
    ans = 0

    potentials = [0] * n2  # to adjust negative edge for dijkstra
    predecessors_v = [0] * n2
    predecessors_i = [0] * n2

    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_v[u] = v
                predecessors_i[u] = 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(n + 1, n2):
            potentials[i] += distances[i]

        # path = [t]
        min_cap = remain
        v = t
        while v != s:
            p = predecessors_v[v]
            i = predecessors_i[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 = predecessors_v[v]
            i = predecessors_i[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])
    ki = n2 - 4
    kc = REV - (rx + ry)
    links[ri].append([ki, INF, kc, len(links[ki])])
    links[ki].append([ri, 0, -kc, len(links[ri]) - 1])
    ki = n2 - 3
    kc = REV - (-rx + ry)
    links[ri].append([ki, INF, kc, len(links[ki])])
    links[ki].append([ri, 0, -kc, len(links[ri]) - 1])
    ki = n2 - 2
    kc = REV - (rx - ry)
    links[ri].append([ki, INF, kc, len(links[ki])])
    links[ki].append([ri, 0, -kc, len(links[ri]) - 1])
    ki = n2 - 1
    kc = REV - (-rx - 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])
    ki = n2 - 4
    kc = REV - (-bx - by)
    links[ki].append([bi, INF, kc, len(links[bi])])
    links[bi].append([ki, 0, -kc, len(links[ki]) - 1])
    ki = n2 - 3
    kc = REV - (bx - by)
    links[ki].append([bi, INF, kc, len(links[bi])])
    links[bi].append([ki, 0, -kc, len(links[ki]) - 1])
    ki = n2 - 2
    kc = REV - (-bx + by)
    links[ki].append([bi, INF, kc, len(links[bi])])
    links[bi].append([ki, 0, -kc, len(links[ki]) - 1])
    ki = n2 - 1
    kc = REV - (bx + 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, n, n2, INF, REV))

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def min_cost_flow(links, s, t, flow, n, n2, INF, REV):
    remain = flow
    ans = 0

    potentials = [0] * n2  # to adjust negative edge for dijkstra
    predecessors_v = [0] * n2
    predecessors_i = [0] * n2

    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_v[u] = v
                predecessors_i[u] = 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(n + 1, n2):
            potentials[i] += distances[i]

        # path = [t]
        min_cap = remain
        v = t
        while v != s:
            p = predecessors_v[v]
            i = predecessors_i[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 = predecessors_v[v]
            i = predecessors_i[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, n, n2, INF, REV))

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_v = [0] * n2
    predecessors_i = [0] * n2

    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_v[u] = v
                predecessors_i[u] = 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 = predecessors_v[v]
            i = predecessors_i[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 = predecessors_v[v]
            i = predecessors_i[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))