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
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: Time Limit Exceeded

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 = [(0,source)]
            while q:
                dv,v = heappop(q)
                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,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: Time Limit Exceeded

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 = [(0,source)]
            while q:
                dv,v = heappop(q)
                if dist[v] < dv:
                    continue
                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,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: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def min_cost_flow(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
    res = 0
    while f > 0:
        dist = [1<<100] * NN
        dist[s] = 0
        update = 1
        while update:
            update = 0
            for v in range(NN):
                if dist[v] == 1<<100: continue
                for i, (b, _cap, c, r) in enumerate(G[v]):
                    if _cap > 0 and dist[b] > dist[v] + c:
                        dist[b] = dist[v] + c
                        prevv[b] = v
                        preve[b] = i
                        update = 1
        if dist[t] == 1<<100:
            return -1
        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(E, 2*N+4, 2*N+5, su))

Submission status: Time Limit Exceeded

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, (0, s))
        while q:
            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_dijkstra(E, 2*N+4, 2*N+5, su))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def min_cost_flow(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
    res = 0
    while f > 0:
        dist = [1<<100] * NN
        dist[s] = 0
        update = 1
        while update:
            update = 0
            for v in range(NN):
                if dist[v] == 1<<100: continue
                for i, (b, _cap, c, r) in enumerate(G[v]):
                    if _cap > 0 and dist[b] > dist[v] + c:
                        dist[b] = dist[v] + c
                        prevv[b] = v
                        preve[b] = i
                        update = 1
        if dist[t] == 1<<100:
            return -1
        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(E, 2*N+4, 2*N+5, su))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def min_cost_flow(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
    res = 0
    while f > 0:
        dist = [1<<100] * NN
        dist[s] = 0
        update = 1
        while update:
            update = 0
            for v in range(NN):
                if dist[v] == 1<<100: continue
                for i, (b, _cap, c, r) in enumerate(G[v]):
                    if _cap > 0 and dist[b] > dist[v] + c:
                        dist[b] = dist[v] + c
                        prevv[b] = v
                        preve[b] = i
                        update = 1
        if dist[t] == 1<<100:
            return -1
        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 = 0
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: Time Limit Exceeded

Solution code:
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):
        inf=10**10
        n,E=self.n,self.edges
        prev_v,prev_e=[0]*n,[0]*n
        mincost=0
        while flow:
            dist=[inf]*n
            dist[source]=0
            flag=True
            while flag:
                flag=False
                for v in range(n):
                    if dist[v]==inf:
                        continue
                    Ev=E[v]
                    for i in range(len(Ev)):
                        to,cap,cost,rev=Ev[i]
                        if cap>0 and dist[v]+cost<dist[to]:
                            dist[to]=dist[v]+cost
                            prev_v[to],prev_e[to]=v,i
                            flag=True
            if dist[sink]==inf:
                return -1
            f=flow
            v=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

def main():
    import sys
    input=sys.stdin.readline
    n=int(input())
    flow=MinCostFlow(2*n+6)
    k=2*10**9
    f=10**5
    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,f,-rx-ry+k)
        flow.add_edge(i+1,n+2,f,rx-ry+k)
        flow.add_edge(i+1,n+3,f,-rx+ry+k)
        flow.add_edge(i+1,n+4,f,rx+ry+k)
    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,f,bx+by+k)
        flow.add_edge(n+2,n+5+i,f,-bx+by+k)
        flow.add_edge(n+3,n+5+i,f,bx-by+k)
        flow.add_edge(n+4,n+5+i,f,-bx-by+k)
    print(-(flow.MinCost(0,2*n+5,s))+2*s*k)

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline

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):
        inf=10**10
        n,E=self.n,self.edges
        prev_v,prev_e=[0]*n,[0]*n
        mincost=0
        while flow:
            dist=[inf]*n
            dist[source]=0
            flag=True
            while flag:
                flag=False
                for v in range(n):
                    if dist[v]==inf:
                        continue
                    Ev=E[v]
                    for i in range(len(Ev)):
                        to,cap,cost,rev=Ev[i]
                        if cap>0 and dist[v]+cost<dist[to]:
                            dist[to]=dist[v]+cost
                            prev_v[to],prev_e[to]=v,i
                            flag=True
            if dist[sink]==inf:
                return -1
            f=flow
            v=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)
k=2*10**9
f=10**5
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,f,-rx-ry+k)
    flow.add_edge(i+1,n+2,f,rx-ry+k)
    flow.add_edge(i+1,n+3,f,-rx+ry+k)
    flow.add_edge(i+1,n+4,f,rx+ry+k)
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,f,bx+by+k)
    flow.add_edge(n+2,n+5+i,f,-bx+by+k)
    flow.add_edge(n+3,n+5+i,f,bx-by+k)
    flow.add_edge(n+4,n+5+i,f,-bx-by+k)
print(-(flow.MinCost(0,2*n+5,s))+2*s*k)

Submission status: Time Limit Exceeded

Solution code:
# Dijkstra's algorithm with Priority Heap and Potential

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 = [s]
        updated = [False] * N_
        updated[s] = True

        while que :
            v = heappop(que)
            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 + H[v] - H[w] :
                    dist[w] = dist[v] + cost + H[v] - H[w]
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, w)
                    updated[w] = True

        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(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: Time Limit Exceeded

Solution code:
# Dijkstra's algorithm with Priority Heap and Potential

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]
        updated = [False] * N_

        while que :
            v = heappop(que)
            updated[v] = False
            if updated[v] :
                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] = dist[v] + cost + H[v] - H[w]
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, w)
                    updated[w] = True

        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(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: 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] = dist[v] + cost + H[v] - H[w]
                    pre_v[w], pre_e[w] = v, i
                    heappush(que, (dist[w], 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(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: 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 :
                    r = dist[v] + cost + H[v] - H[w]
                    if r < dist[w] :
                        dist[w] = r
                        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))