Problem:


Score : 500 points

Problem Statement

In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads.
The following are known about the road network:

People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.

Different roads may have had different lengths, but all the lengths were positive integers.

Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom.
He thought that it represented the shortest distances between the cities along the roads in the kingdom.

Determine whether there exists a road network such that for each u and v, the integer A_{u, v} at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v.
If such a network exist, find the shortest possible total length of the roads.

Constraints

1 \leq N \leq 300

If i ≠ j, 1 \leq A_{i, j} = A_{j, i} \leq 10^9.

A_{i, i} = 0

Inputs

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}
...
A_{N, 1} A_{N, 2} ... A_{N, N}

Outputs

If there exists no network that satisfies the condition, print -1.
If it exists, print the shortest possible total length of the roads.

Sample Input 1

3
0 1 3
1 0 2
3 2 0

Sample Output 1

3

The network below satisfies the condition:

City 1 and City 2 is connected by a road of length 1.

City 2 and City 3 is connected by a road of length 2.

City 3 and City 1 is not connected by a road.

Sample Input 2

3
0 1 3
1 0 1
3 1 0

Sample Output 2

-1

As there is a path of length 1 from City 1 to City 2 and City 2 to City 3, there is a path of length 2 from City 1 to City 3.
However, according to the table, the shortest distance between City 1 and City 3 must be 3.

Thus, we conclude that there exists no network that satisfies the condition.

Sample Input 3

5
0 21 18 11 28
21 0 13 10 26
18 13 0 23 13
11 10 23 0 17
28 26 13 17 0

Sample Output 3

82

Sample Input 4

3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0

Sample Output 4

3000000000



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


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()

A = [LIST() for _ in range(N)]
graph = csr_matrix(A)
dist_matrix = floyd_warshall(graph, directed=False)

ans = 0
for i in range(N-1):
    for j in range(i+1, N):
        if A[i][j] != dist_matrix[i][j]:
            print(-1)
            exit()
        for k in range(N):
            if i == k or j == k:
                continue
            if A[i][k] + A[k][j] == A[i][j]:
                break
        else:
            ans += A[i][j]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()

A = [LIST() for _ in range(N)]
graph = csr_matrix(A)
dist_matrix = floyd_warshall(graph, directed=False)

ans = 0 
for i, j in combinations(range(N), 2):
    if A[i][j] != dist_matrix[i][j]:
        print(-1)
        break
    for k in range(N):
        if i == k or j == k:
            continue
        if A[i][k] + A[k][j] == A[i][j]:
            break
    else:
        ans += A[i][j]
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
INF=10**18
n=int(input())
a=[list(map(int,input().split())) for _ in range(n)]
c=deepcopy(a)
for k in range(n):
  for i in range(n):
    for j in range(n):
      c[i][j]=min(c[i][j],c[i][k]+c[k][j])
for i in range(n):
  for j in range(n):
    if a[i][j]!=c[i][j]:
      print(-1)
      exit()
ans=0
for i in range(n):
  for j in range(n):
    for k in range(n):
      if k==j or k==i:continue
      if c[i][j]==c[i][k]+c[k][j]:break
    else:ans+=c[i][j]
print(ans//2)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
is_neighbor = [[True] * n for i in range(n)]

f = True
for i in range(n):
    if not f: break
    for s in range(n):
        if not f: break
        for t in range(n):
            if a[s][t] > a[s][i] + a[i][t]:
                f = False
                break
            elif i == s or i == t: continue
            elif a[s][t] == a[s][i] + a[i][t]:
                is_neighbor[s][t] = False
if f:
    ans = 0
    for i in range(n):
        for j in range(n):
            if is_neighbor[i][j]:
                ans+=a[i][j]
    print(ans//2)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A = [list(map(int, input().split())) for i in range(N)]
result=0
flag=True
isbreak=False
for m in range(N-1):
    for n in range(m+1,N):
        list_t=list(range(N))
        list_t.remove(m)
        list_t.remove(n)
        for t in list_t:
            if A[m][n]>A[m][t]+A[t][n]:
                result=-1                
                isbreak=True
                break
            elif A[m][n]==A[m][t]+A[t][n] and result!=-1:
                flag=False
                break
        if flag and result!=-1:
            result+=A[m][n]
        else:
            flag=True
        if isbreak:
            break
    if isbreak:
        break
print(result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
mat = []
for _ in range(n):
  mat.append(list(map(int,input().split())))

d = [[False]*n for _ in range(n)]

for k in range(n):
  for i in range(n):
    for j in range(n):
      if mat[i][j] > mat[i][k]+mat[k][j]:
        print(-1)
        exit()

      if mat[i][j] == mat[i][k]+mat[k][j] and mat[i][k]>0 and mat[k][j]>0:
        d[i][j] = True

ans = 0
for i in range(n):
  for j in range(i+1, n):
    if not d[i][j]:
      ans += mat[i][j]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = int(input())
    m = [list(map(int, input().split())) for _ in range(n)]

    ans = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            d = m[i][j]
            t = min(m[i][k] + m[k][j] if k != i and k != j else d + 1 for k in range(n))
            if t < d:
                print(-1)
                exit()
            if d < t:
                ans += d

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    import heapq
    n = int(readline())
    dist = [[INF] * n for _ in range(n)]
    hq = []
    table = [[0] * n for _ in range(n)]

    for i in range(n):
        a = list(map(int, readline().split()))
        for j in range(i + 1, n):
            hq.append((a[j], i, j))
            table[i][j] = a[j]

    for i in range(n):
        dist[i][i] = 0

    heapq.heapify(hq)
    ans = 0
    while hq:
        cost, u, v = heapq.heappop(hq)
        cur = dist[u][v]
        if cur > cost:
            ans += cost
            dist[u][v] = cost
            for i in range(n):
                dist[i][v] = min(dist[i][v], dist[i][u] + cost)
                dist[i][u] = min(dist[i][u], dist[i][v] + cost)
                for j in range(n):
                    dist[i][j] = min(dist[i][j], dist[i][u] + dist[u][j], dist[i][v] + dist[v][j])

    for i in range(n):
        for j in range(i + 1, n):
            if dist[i][j] != table[i][j]:
                print(-1)
                sys.exit()

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=[list(map(int,input().split())) for _ in range(n)]
ans=0
for i in range(n-1):
  for j in range(i+1,n):
    flg=True
    for k in range(n):
      if k in (i,j):continue
      if a[i][j]>a[i][k]+a[k][j]:
        print(-1)
        exit()
      elif a[i][j]==a[i][k]+a[k][j]:
        flg=False
    if flg:
      ans+=a[i][j]
      #print(i,j)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc074/tasks/arc083_b

import sys
input = sys.stdin.buffer.readline

def floyd_warshall(V, dist):                                               # 動的計画法。頂点 k まで経由することが可能な場合の最短距離という部分問題を考えて、k = 0 から漸化式的に計算する
    res = 0
    for i in range(V):
        for j in range(i+1,V):
            flg = 0
            for k in range(V):
                if k==i or k==j:
                    continue
                if dist[i][j] > dist[i][k] + dist[k][j]:
                    return -1
                if dist[i][j] < dist[i][k] + dist[k][j]:
                    flg += 1
                if flg == V-2:
                    res += dist[i][j]
    return res

N = int(input())

dist = [list(map(int, input().split())) for _ in range(N)]

if N ==2:
    print(dist[0][1])
else:
    print(floyd_warshall(N, dist))

Submission status: Time Limit Exceeded

Solution code:
#!python3

LI = lambda: list(map(int, input().split()))

# input
N = int(input())
A = [LI() for _ in range(N)]


def main():
    ans = 0
    for i in range(N):
        for j in range(N):
            flag = True
            for k in range(N):
                if i == k or j == k:
                    continue
                d = A[i][k] + A[k][j]
                if A[i][j] > d:
                    print(-1)
                    return
                if A[i][j] == d:
                    flag = False
            if flag:
                ans += A[i][j]
    ans //= 2
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def main():
    N = int(readline())
    G = [list(map(int, readline().split())) for _ in range(N)]

    H = [[True] * N for _ in range(N)]
    for k in range(N):
        for i in range(N):
            for j in range(i + 1, N):
                if G[i][j] > G[i][k] + G[k][j]:
                    print(-1)
                    return
                if k not in (i, j) and G[i][j] == G[i][k] + G[k][j]:
                    H[i][j] = False

    ans = 0
    for i in range(N):
        for j in range(i + 1, N):
            if H[i][j]:
                ans += G[i][j]

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=[list(map(int,input().split()))for _ in range(n)]
b=[i.copy() for i in a]
c=[n*[1]for _ in range(n)]
for k in range(n):
  for i in range(n):
    for j in range(n):
      b[i][j]=min(b[i][j],b[i][k]+b[k][j])
      if a[i][j]==a[i][k]+a[k][j]:
        if i!=j and i!=k and j!=k:
          c[i][j]=0
if a!=b:exit(print(-1))
ans=0
for i in range(n):
  for j in range(i):
    if c[i][j]:ans+=a[i][j]
print(ans)

Submission status: Time Limit Exceeded

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

N = int(readline())

A = [None] * N
for i in range(N):
  A[i] = list(map(int,readline().split()))
  
# まずワーシャルフロイド表を作る
# ワーシャルフロイド表より大きな数値が元の表にあったら、最短距離の表ではないので-1
# 最短距離の表になっているのであれば、
# A[1][3]に行くときにA[1][2] + A[2][3]となるのであれば、
# A[1][3]のほうだけansに記録していく

import copy
newA = copy.deepcopy(A)

for k in range(N):
  for i in range(N):
    for j in range(N):
      if i == k or k == j or i == j:
        continue
      if A[i][k] + A[k][j] < A[i][j]:
        print(-1)
        exit(0)
      elif A[i][k] + A[k][j] == A[i][j]:
        # A[i][j]の道路は不要
        newA[i][j] = 0

ans = 0
for a in newA:
  ans += sum(a)
print(ans // 2)

Submission status: Time Limit Exceeded

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

N = int(readline())

A = [None] * N
for i in range(N):
  A[i] = list(map(int,readline().split()))
  
# まずワーシャルフロイド表を作る
# ワーシャルフロイド表より大きな数値が元の表にあったら、最短距離の表ではないので-1
# 最短距離の表になっているのであれば、
# A[1][3]に行くときにA[1][2] + A[2][3]となるのであれば、
# A[1][3]のほうだけansに記録していく

import numpy as np
from scipy.sparse.csgraph import shortest_path
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse.csgraph import csgraph_from_dense
A = np.array(A)
G = csgraph_from_dense(A, null_value=0)
w = floyd_warshall(G)

for i in range(N):
  for j in range(N):
    if A[i][j] > w[i][j]:
      print(-1)
      exit(0)

ans = 0
for a in A:
  ans += sum(a)
  
for k in range(N):
  for i in range(N):
    for j in range(N):
      if i == k or k == j or i == j:
        continue
      if A[i][k] + A[k][j] == A[i][j]:
        ans -= A[i][j]
        
print(ans // 2)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush
input = sys.stdin.readline

def main():
    n = int(input())
    a = [list(map(int,input().split())) for _ in range(n)]
    g = [[] for _ in range(n)]
    for i in range(n-1):
        for j in range(i+1,n):
            g[i].append((j,a[i][j]))
            g[j].append((i,a[i][j]))
    ans = 0
    for i in range(n):
        ans += sum(a[i])
    ans //= 2
    for i in range(n-1):
        que = []
        d = [10**15 for _ in range(n)]
        d[i] = 0
        heappush( que,(0,i) )
        while que:
            p =  heappop(que)
            v = p[1]
            if d[v] < p[0]:
                continue
            for k in range(len(g[v])):
                edge = g[v][k]
                if d[edge[0]] > d[v] + edge[1]:
                    d[edge[0]] = d[v] + edge[1]
                    heappush( que,(d[edge[0]] , edge[0]) )
        if d != a[i]:
            print(-1)
            return
        for j in range(i+1,n):
            que = []
            d = [10**15 for _ in range(n)]
            d[i] = 0
            heappush( que,(0,i) )
            while que:
                p =  heappop(que)
                v = p[1]
                if d[v] < p[0]:
                    continue
                for k in range(len(g[v])):
                    edge = g[v][k]
                    if (edge[0], v) == (i,j) or (edge[0], v) == (j,i):
                        continue
                    if d[edge[0]] > d[v] + edge[1]:
                        d[edge[0]] = d[v] + edge[1]
                        heappush( que,(d[edge[0]] , edge[0]) )
            if d[j] == a[i][j]:
                ans -= a[i][j]
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush
input = sys.stdin.readline

def dijkstra(s,n,g):
    que = []
    d = [10**15 for _ in range(n)]
    d[s] = 0
    heappush( que,(0,s) )
    while que:
        p =  heappop(que)
        v = p[1]
        if d[v] < p[0]:
            continue
        for i in range(len(g[v])):
            edge = g[v][i]
            if d[edge[0]] > d[v] + edge[1]:
                d[edge[0]] = d[v] + edge[1]
                heappush( que,(d[edge[0]] , edge[0]) )
    return d

def dijkstra1(s,ss,n,g):
    que = []
    d = [10**15 for _ in range(n)]
    d[s] = 0
    heappush( que,(0,s) )
    while que:
        p =  heappop(que)
        v = p[1]
        if d[v] < p[0]:
            continue
        for i in range(len(g[v])):
            edge = g[v][i]
            if (edge[0], v) == (s,ss) or (edge[0], v) == (ss,s):
                continue
            if d[edge[0]] > d[v] + edge[1]:
                d[edge[0]] = d[v] + edge[1]
                heappush( que,(d[edge[0]] , edge[0]) )
    return d

def main():
    n = int(input())
    a = [list(map(int,input().split())) for _ in range(n)]
    g = [[] for _ in range(n)]
    for i in range(n-1):
        for j in range(i+1,n):
            g[i].append((j,a[i][j]))
            g[j].append((i,a[i][j]))
    ans = 0
    for i in range(n):
        ans += sum(a[i])
    ans //= 2
    for i in range(n-1):
        d = dijkstra(i,n,g)
        if d != a[i]:
            print(-1)
            return
        for j in range(i+1,n):
            d = dijkstra1(i,j,n,g)
            if d[j] == a[i][j]:
                ans -= a[i][j]
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    # d[i][j]は2頂点間i, j間の移動コストを格納, Vは頂点数
    def warshall_floyd2(s, d, V):
        for i in range(V):
            for j in range(V):
                d[i][j] = min(d[i][j], d[i][s] + d[s][j])
        for k in range(V):
            for j in range(V):
                d[s][j] = min(d[s][j], d[s][k] + d[k][j])
        for k in range(V):
            for i in range(V):
                d[i][s] = min(d[i][s], d[i][k] + d[k][s])
        return d # d[i][j]に頂点i, j間の最短距離を格納

    n = int(input())
    a = [list(map(int,input().split())) for _ in range(n)]

    d = [[10**10] * n for _ in range(n)]
    dis = []
    ans = 0
    for i in range(n):
        for j in range(i+1, n):
            dis.append((a[i][j], (i,j)))

    dis.sort()

    for dis1, p in dis:
        d = warshall_floyd2(p[0], d, n)
        if d[p[0]][p[1]] == 10**10:
            d[p[0]][p[1]] = a[p[0]][p[1]]
            d[p[1]][p[0]] = a[p[0]][p[1]]
            ans += dis1
        else:
            if d[p[0]][p[1]] < dis1:
                print(-1)
                exit()
            elif d[p[0]][p[1]] > dis1:
                d[p[0]][p[1]] = a[p[0]][p[1]]
                d[p[1]][p[0]] = a[p[0]][p[1]]
                ans += dis1
        #d = warshall_floyd2(p[1], d, n)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# d[i][j]は2頂点間i, j間の移動コストを格納, Vは頂点数
def warshall_floyd2(s, d, V):
    for i in range(V):
        for j in range(V):
            d[i][j] = min(d[i][j], d[i][s] + d[s][j])
    for k in range(V):
        for j in range(V):
            d[s][j] = min(d[s][j], d[s][k] + d[k][j])
    for k in range(V):
        for i in range(V):
            d[i][s] = min(d[i][s], d[i][k] + d[k][s])
    return d # d[i][j]に頂点i, j間の最短距離を格納

n = int(input())
a = [list(map(int,input().split())) for _ in range(n)]

d = [[10**10] * n for _ in range(n)]
dis = []
ans = 0
for i in range(n):
    for j in range(i+1, n):
        dis.append((a[i][j], (i,j)))

dis.sort()

for dis1, p in dis:
    d = warshall_floyd2(p[0], d, n)
    if d[p[0]][p[1]] == 10**10:
        d[p[0]][p[1]] = a[p[0]][p[1]]
        d[p[1]][p[0]] = a[p[0]][p[1]]
        ans += dis1
    else:
        if d[p[0]][p[1]] < dis1:
            print(-1)
            exit()
        elif d[p[0]][p[1]] > dis1:
            d[p[0]][p[1]] = a[p[0]][p[1]]
            d[p[1]][p[0]] = a[p[0]][p[1]]
            ans += dis1
    d = warshall_floyd2(p[1], d, n)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

n = int(input())
a = [list(map(int,input().split())) for _ in range(n)]

edges = [[] for _ in range(n)]
dis = []
ans = 0
for i in range(n):
    for j in range(i+1, n):
        dis.append((a[i][j], (i,j)))

dis.sort()

def dijkstra(edges, s):
    hq = []
    d = [-1] * n
    d[s] = 0
    heapq.heappush(hq, (0, s))
    while hq:
        d1, p = heapq.heappop(hq)
        for p2, d2 in edges[p]:
            if d[p2] == -1 or d[p2] > d1 + d2:
                d[p2] = d1 + d2
                heapq.heappush(hq, (d1+d2, p2))
    return d

for dis1, p in dis:
    d = dijkstra(edges, p[0])
    if d[p[1]] == -1:
        edges[p[0]].append((p[1], dis1))
        edges[p[1]].append((p[0], dis1))
        ans += dis1
    else:
        if d[p[1]] < dis1:
            print(-1)
            exit()
        elif d[p[1]] > dis1:
            edges[p[0]].append((p[1], dis1))
            edges[p[1]].append((p[0], dis1))
            ans += dis1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import copy
N = int(input())
A = [list(map(int, input().split())) for i in range(N)]
B = A

def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    ans = 0
    for k in range(N):
        for i in range(N):
            for j in range(N):
               # if d[i][j] == d[i][k] + d[k][j]:
               #   if (i != k) and (j != k):
               #     ans += d[i][j]
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

##############################

#d = [[float("inf") for i in range(10)] for i in range(10)] 
#d[u][v] : 辺uvのコスト(存在しないときはinf)
#for i in range(10):
#  for j in range(10):
#    d[i][j] = C[i][j]

#print(warshall_floyd(d))
#print(warshall_floyd(C))
B = copy.deepcopy(A)
cost = warshall_floyd(B)
#print(cost , A)

ans = 0
for i in range(N):
  for j in range(N):
    if cost[i][j] < A[i][j]:
      print("-1")
      quit()

for i in range(N):
  cost[i][i] = 10 ** 18
for i in range(N):
  for j in range(N):
    p = 1
    for k in range(N):
      if cost[i][j] >= cost[i][k] + cost[k][j]:
        p = 0
        break
    if p == 1:
      ans += cost[i][j]


ans = ans / 2
#for i in range(10):
#  ans += num[i] * cost[i][1]

print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
import copy
from itertools import product, combinations

N = int(input())

dp = []
for _ in range(N):
    dp.append(list(map(int, input().split(' '))))

original = copy.deepcopy(dp)

for k, i, j in product(range(N), repeat=3):
    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])

if dp == original:
    cost = 0
    for i in range(N):
        for j in range(i + 1, N):
            for k in range(N):
                if k == i or k == j:
                    continue
                if dp[i][j] == dp[i][k] + dp[k][j]:
                    break
            else:
                cost += dp[i][j]
    print(cost)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import copy
from itertools import product, combinations

N = int(input())

dp = []
for _ in range(N):
    dp.append(list(map(int, input().split(' '))))

original = copy.deepcopy(dp)


for k, i, j in product(range(N), repeat=3):
    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])

if dp == original:
    route_set = set()
    costs = []
    for i in range(N):
        for j in range(i + 1, N):
            route_set.add(dp[i][j])
            costs.append(dp[i][j])

    route_set = route_set - set(map(sum, combinations(costs, r=2)))
    print(sum([cost for cost in costs if cost in route_set]))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product, combinations
import numpy as np

N = int(input())

dp = np.zeros(shape=(N, N), dtype=int)

for i in range(N):
    dp[i] = np.array(list(map(int, input().split(' '))))

original = dp.copy()

for k, i in product(range(N), repeat=2):
    dp[i] = np.minimum(dp[i], dp[i][k] + dp[k])

if np.all(dp == original):
    route_set = set()
    costs = []
    for i in range(N):
        for j in range(i + 1, N):
            route_set.add(dp[i][j])
            costs.append(dp[i][j])

    route_set = route_set - set(map(sum, combinations(costs, r=2)))
    print(sum([cost for cost in costs if cost in route_set]))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import bisect
from itertools import product
import numpy as np

N = int(input())

dp = np.zeros(shape=(N, N), dtype=int)

for i in range(N):
    dp[i] = np.array(list(map(int, input().split(' '))))

original = dp.copy()

for k, i in product(range(N), repeat=2):
    dp[i] = np.minimum(dp[i], dp[i][k] + dp[k])

if not np.all(dp == original):
    print(-1)
else:
    costs = []
    for i in range(N):
        for j in range(i + 1, N):
            costs.append(dp[i][j])
    costs.sort()
    duplicated = set()
    for i in range(len(costs) - 1):
        if costs[i] in duplicated:
            continue
        for j in range(i + 1, len(costs)):
            if costs[j] in duplicated:
                continue
            index = bisect.bisect_left(costs, costs[i] + costs[j])
            if index < len(costs) and costs[index] == costs[i] + costs[j]:
                duplicated.add(costs[index])
    print(sum([cost for cost in costs if cost not in duplicated]))

Submission status: Time Limit Exceeded

Solution code:
from itertools import product, combinations
import numpy as np

N = int(input())

dp = np.zeros(shape=(N, N), dtype=int)

for i in range(N):
    dp[i] = np.array(list(map(int, input().split(' '))))

original = dp.copy()

for k, i in product(range(N), repeat=2):
    dp[i] = np.minimum(dp[i], dp[i][k] + dp[k])

if not np.all(dp == original):
    print(-1)
else:
    costs = []
    for i in range(N):
        for j in range(i + 1, N):
            costs.append(dp[i][j])
    sum_set = set(map(sum, combinations(costs, r=2)))
    result = 0
    for cost in costs:
        if cost not in sum_set:
            result += cost
    print(result)

Submission status: Time Limit Exceeded

Solution code:

n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
#print(a)

for k in range(n-1,-1,-1):
    for i in range(n-1,-1,-1):
        for j in range(n-1,-1,-1):            
            #print(k,i,j,a)
            if (i==j or k==i or k==j):
                continue
            if (a[i][k]!=-1 and a[k][j]!=-1 and a[i][j] == a[i][k]+a[k][j]):
                a[i][j] = -1
            elif (a[i][k]!=-1 and a[k][j]!=-1 and a[i][j] > a[i][k]+a[k][j]):
                print(-1)
                exit()
            
#print(a)

ans = 0
for i in range(0,n-1):
    for j in range(i,n):
        if (a[i][j]!=-1):
            ans += a[i][j]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=[list(map(int,input().split())) for i in range(N)]

ans = 0
for i in range(N):
    for j in range(i + 1, N):
        ok = True
        for k in range(N):
            if i == k or j == k:
                continue
            if A[i][j] > A[i][k] + A[k][j]:
                print(-1)
                exit(0)
            elif A[i][j] == A[i][k] + A[k][j]:
                ok = False
        if ok:
            ans += A[i][j]

print(ans)