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: Wrong Answer

Solution code:
# 63


n = int(input())
dp = [[int(x) for x in input().split()] for y in range(n)]
del_l = []
ans = 0

for i in range(n):
    for j in range(i+1,n):
        ans += dp[i][j]

for i in range(n-1):
    for j in range(i+1,n):
        for k in range(n):
            if k in (i,j):
                continue
            if dp[i][j] > dp[i][k] + dp[k][j]:
                print("-1")
                exit()
            elif dp[i][j] == dp[i][k] + dp[k][j]:
                ans -= dp[i][j]

print(ans)

Submission status: Wrong Answer

Solution code:
# 63


n = int(input())
dp = [[int(x) for x in input().split()] for y in range(n)]
flag = True
del_l = []
ans = 0

for i in range(n):
    for j in range(i+1,n):
        ans += dp[i][j]

for k in range(n):
    for j in range(n):
        for i in range(n):
            if dp[i][j] > dp[i][k] + dp[k][j]:
                print("-1")
                flag = False
                break
            elif (dp[i][j] == dp[i][k] + dp[k][j]) and (i != k and j != k) and (i < j):
#                 print(i,j,dp[i][j])
                ans -= dp[i][j]
        if not flag:
            break
    if not flag:
        break

if flag:
    print(ans)

Submission status: Wrong Answer

Solution code:
# 63


n = int(input())
dp = [[int(x) for x in input().split()] for y in range(n)]
flag = True
del_l = []
ans = 0

for i in range(n):
    for j in range(i+1,n):
        ans += dp[i][j]

for k in range(n):
    for j in range(n):
        for i in range(n):
            if dp[i][j] > dp[i][k] + dp[k][j]:
                print("-1")
                flag = False
                break
            elif (dp[i][j] == dp[i][k] + dp[k][j]) and (i != k and j != k) and (i < k):
                ans -= dp[i][j]
        if not flag:
            break
    if not flag:
        break

if flag:
    print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[List[int]]"):
    import numpy as np
    from scipy.sparse.csgraph import floyd_warshall
    A = np.array(A, dtype=np.float64)
    B = floyd_warshall(A, directed=True)
    if not np.array_equal(A, B):
        return -1
    delta = 10e-10
    _, pre = floyd_warshall(A-delta+np.identity(N)*delta, return_predecessors=True)
    return int(A[pre == [[i]*N for i in range(N)]].sum()) // 2

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(N)] for _ in range(N)]  # type: "List[List[int]]"
    print(solve(N, A))

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[List[int]]"):
    import numpy as np
    from scipy.sparse.csgraph import floyd_warshall
    A = np.array(A, dtype=np.float64)
    B = floyd_warshall(A, directed=True)
    if not np.array_equal(A, B):
        return -1
    delta = 10e-10
    _, pre = floyd_warshall(A-delta, directed=True, return_predecessors=True)
    return int(A.sum() - A[pre != [[i]*N for i in range(N)]].sum()) // 2

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(N)] for _ in range(N)]  # type: "List[List[int]]"
    print(solve(N, A))

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop
INF=10**20

def warshall_floyd(A_):
    d_ = [[INF for i in range(len(A_))] for j in range(len(A_))]
    for i in range(len(A_)):
        d_[i][i] = 0

    for k in range(len(A_)):
        for i in range(len(A_)):
            for j in range(len(A_)):
                if A_[i][j] != 0:
                    d_[i][j] = A_[i][j]
                d_[i][j] = min(d_[i][j], d_[i][k]+d_[k][j])
    
    return d_
  
def dijkstra(G, start = 0):
    
    d_ = [INF for i in range(len(G))]
    d_[start] = 0
    
    que = []
    heappush(que, (0, start))

    while len(que) != 0:
        p = heappop(que)
        v = p[1]
        
        if d_[v] < p[0]:
            continue
            
        for u in range(len(G[v])):
            if G[v][u]==0:continue
            if d_[u] > d_[v] + G[v][u]:
                d_[u] = d_[v] + G[v][u]
                heappush(que, (d_[u], u))
    
    return d_

N=int(input())
A=[list(map(int,input().split())) for _ in range(N)]
dist=[]
for i in range(N-1):
  for j in range(i+1,N):
    heappush(dist,(A[i][j],i,j))
    
B=[[0 for _ in range(N)] for _ in range(N)]
connected = [False for _ in range(N+1)]

d,v1,v2 = heappop(dist)
B[v1][v2] = B[v2][v1] = d
connected[v1]=connected[v2]=True
while len(dist):
  d,v1,v2 = heappop(dist)
  if connected[v1]+connected[v2]==1:
    B[v1][v2] = B[v2][v1] = d
    connected[v1]=connected[v2]=True
  elif connected[v1]+connected[v2]==2:
    d_tmp = dijkstra(B,v1)[v2]
    if d < d_tmp:
      B[v1][v2] = B[v2][v1] = d

A2 = warshall_floyd(B)
ans=0
for i in range(N-1):
  for j in range(i+1,N):
    if A[i][j] != A2[i][j]:
      print(-1)
      exit()
    ans += A2[i][j]
    
print(ans//2)

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

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

    """
    まず三角不等式が任意の３頂点に対して成り立つことを確認する。
    なりたってなければグラフは存在しない。

    なりたっている場合は与えられた最短距離と同じ長さの辺を各頂点のペアごとに張れば
    一応条件を満たすグラフは構成できている。

    あとはここから余分な辺をどう削除するかだが、これは三角不等式で統合が成り立っているもの
    として判別できる。
    """

    # 三角不等式チェック
    triangle = True
    unused_path = set()
    for i in range(N):
        for j in range(N):
            for k in range(N):
                if i == j or j == k or k == i: continue
                if A[i][j] + A[j][k] < A[i][k]:
                    triangle = False
                    break
                elif A[i][j] + A[j][k] == A[i][k]:
                    i, k = min(i, k), max(i, k)
                    unused_path.add((i, k))
    if not triangle:
        print(-1)
        return
    
    # 辺の削除
    ans = 0
    for i in range(N): ans += sum(A[i])
    ans //= 2
    for i, k in unused_path: ans -= A[i][k]
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
import numpy as np

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    N = int(readline())
    A = list(list(map(int, readline().split())) for _ in range(N))
    A = np.array(A)
    D = dijkstra(A)
    if (A!=D).any():
        print(-1)
    else:
        ans = 0
        D += np.identity(N, int) * (10**10)
        for i in range(N):
            for j in range(i + 1, N):
                a = np.min(D[i] + D[j])
                print(D[i])
                if a > D[i, j]:
                    ans += D[i, j]
        print(int(ans))



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from copy import deepcopy
from collections import defaultdict
readline=sys.stdin.readline
read=sys.stdin.read

def main():
    n=int(readline())
    a=[list(map(int,l.split())) for l in read().splitlines()]
    cost=deepcopy(a)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j])
    s=0
    for i in range(n):
        for j in range(i+1,n):
            if cost[i][j]<a[i][j]:
                print(-1)
                return None
            p=[cost[i][k]+cost[k][j]-cost[i][j] for k in range(n) if k!=i and k!=j]
            if p:
                if min(p)>0:
                    s+=a[i][j]
    print(s)

if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [[0 for _ in range(N+1)]]
for _ in range(N):
    a = list(map(int,input().split()))
    a.insert(0,0)
    A.append(a)
tot = 0
for i in range(1,N):
    for j in range(i,N+1):
        tot += A[i][j]
for i in range(1,N):
    for j in range(i+1,N+1):
        for k in range(1,N+1):
            if k!=i and k!=j:
                if A[i][j]>A[i][k]+A[k][j]:
                    tot = -1
                    break
                elif A[i][j]==A[i][k]+A[k][j]:
                    tot -= A[i][j]
                    break
        if tot<0:break
print(tot)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [[0 for _ in range(N+1)]]
for _ in range(N):
    a = list(map(int,input().split()))
    a.insert(0,0)
    A.append(a)
tot = 0
for i in range(1,N):
    for j in range(i,N+1):
        tot += A[i][j]
for i in range(1,N):
    for j in range(i+1,N+1):
        for k in range(1,N+1):
            if k!=i and k!=j:
                if A[i][j]>A[i][k]+A[k][j]:
                    tot = -1
                    break
                elif A[i][j]==A[i][k]+A[k][j]:
                    tot -= A[i][j]
        if tot<0:break
    if tot<0:break
print(tot)

Submission status: Wrong Answer

Solution code:
import heapq

N = int(input())
A = [list(map(int, input().split())) for _ in range(N)]
used = [[False] * N for _ in range(N)]
ans = 0
for i in range(N):
    for j in range(N):
        via = i
        for k in range(N):
            if A[i][j] > A[i][k] + A[k][j]:
                print(-1)
                exit()
            if k == i or k == j:
                continue
            if A[i][j] == A[i][k] + A[k][j]:
                via = k
        if i >= j:
            continue
        if not (used[i][via] and used[via][i]):
            used[i][via] = True
            used[via][i] = True
            ans += A[i][via]
        if not (used[via][j] and used[j][via]):
            used[via][j] = True
            used[j][via] = True
            ans += A[via][j]
print(ans)

Submission status: Wrong Answer

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

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

def warshall_floyd(v_count: int, matrix: list) -> list:
    for i in range(v_count):
        for j, c2 in enumerate(row[i] for row in matrix):
            for k, (c1, c3) in enumerate(zip(matrix[j], matrix[i])):
                if c1 > c2+c3:
                    matrix[j][k] = c2+c3
    return matrix

A = [LIST() for _ in range(N)]
dist_matrix = warshall_floyd(N, A)

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: Wrong Answer

Solution code:
n = int(input())
a_s = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for a in a_s:
    ans += sum(a)

for i in range(n):
    for j in range(n):
        if i == j:
            continue
        for k in range(n):
            if i == k or j == k:
                continue
            if a_s[i][j] > a_s[i][k] + a_s[j][k]:
                print(-1)
                exit()
            if a_s[i][j] == a_s[i][k] + a_s[j][k]:
                ans -= a_s[i][j]

ans //= 2
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
import sys

INF = 2**120

n = int(input())
d = [[] for j in range(n)]
for j in range(n):
    d[j] = [int(i) for i in input().split()]

ans = sum([sum(d[i]) for i in range(n)])

minus = [[0] * n for i in range(n)]

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]:
                print('-1')
                sys.exit()
            if d[i][j] == d[i][k]+d[k][j] and i != k and j != k:
                print(i, j, k)
                minus[i][j] = 1

for i in range(n):
    for j in range(n):
        if minus[i][j]:
            ans -= d[i][j]

print(ans//2)

Submission status: Wrong Answer

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 i in range(n):
                for j in range(i+1,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: Wrong Answer

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(i + 1, 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: Wrong Answer

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

print(floyd_warshall(N, dist))

Submission status: Wrong Answer

Solution code:
#!python3

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

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

INF = 10 ** 10
links = []


def create_links():
    for i in range(N):
        for j in range(i + 1, N):
            links.append((A[i][j], i, j))
    links.sort()


def solve():
    ans = 0
    w = [[INF] * N for _ in range(N)]
    s = set()
    for a, i, j in links:
        if i in s and j in s:
            if w[i][j] < a:
                return -1
            if w[i][j] > a:
                w[i][j] = w[j][i] = a
                ans += a
                for k in s:
                    if k == i or k == j:
                        continue
                    if w[k][i] > w[k][j] + w[j][i]:
                        w[k][i] = w[i][k] = w[k][j] + w[j][i]
                        if w[k][i] < A[k][i]:
                            return -1
                    if w[k][j] > w[k][i] + w[i][j]:
                        w[k][j] = w[j][k] = w[k][i] + w[i][j]
                        if w[k][j] < A[k][j]:
                            return -1
        elif i in s:
            w[i][j] = w[j][i] = a
            ans += a
            for k in s:
                if k == i:
                    continue
                w[k][j] = w[j][k] = min(w[k][j], w[k][i] + a)
                if w[k][j] < A[k][j]:
                    return -1
            s.add(j)
        elif j in s:
            w[i][j] = w[j][i] = a
            ans += a
            for k in s:
                if k == j:
                    continue
                w[k][i] = w[i][k] = min(w[k][i], w[k][j] + a)
                if w[k][i] < A[k][i]:
                    return -1
            s.add(i)
        else:
            w[i][j] = w[j][i] = a
            ans += a
            s.add(i)
            s.add(j)
    return ans


def main():
    create_links()
    ans = solve()
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout
input = stdin.readline
#print = stdout.write

N = int(input())
A = [[int(i) for i in input().split()] for _ in range(N)]
sumA = sum(sum(A, [])) // 2
correct = True


def isCorrect():
    for u in range(N):
        for v in range(u + 1, N):
            for k in range(N):
                if A[u][k] and A[v][k]:
                    #print(u,v,k,A[u][k],A[v][k],A[u][v])
                    if A[u][k] + A[k][v] < A[u][v]:
                        return False
    return True


if not isCorrect(): print(str(-1))
else:
    for u in range(N):
        for v in range(u + 1, N):
            for k in range(N):
                if A[u][k] and A[k][v]:
                    if A[u][k] + A[k][v] == A[u][v]:
                        sumA -= A[u][v]
                        A[u][v] = 0
                        A[v][u] = 0
                        break
    print(str(sumA))

Submission status: Wrong Answer

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に記録していく

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]:
        print(-1)
        exit(0)
      elif A[i][k] + A[k][j] == A[i][j]:
        ans -= A[i][j]

print(ans // 2)

Submission status: Wrong Answer

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に記録していく

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]:
        print(-1)
        exit(0)
      if A[i][k] + A[k][j] == A[i][j]:
        ans -= A[i][j]
        
print(ans // 2)

Submission status: Wrong Answer

Solution code:
import sys


def warshall_floyd(dist, N):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])


def main():
    N = int(input())
    dp = [[0 for i in range(N)] for j in range(N)]
    dist = [[0 for i in range(N)] for j in range(N)]
    for i in range(N):
        d = [int(c) for c in input().split()]
        for j in range(N):
            dp[i][j] = d[j]
            dist[i][j] = d[j]
    warshall_floyd(dist, N)
    ans = 0
    for i in range(N):
        for j in range(i+1, N):
            if dp[i][j] > dist[i][j]:
                print(-1)
                sys.exit()
            elif dp[i][j] == dist[i][j]:
                ans += dist[i][j]
                for w in range(N):
                    if w != i and w != j:
                        if dist[i][w] + dist[w][j] == dist[i][j]:
                            ans -= dist[i][j]
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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
    w = []
    for i in range(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 d[edge[0]] > d[v] + edge[1]:
                    d[edge[0]] = d[v] + edge[1]
                    heappush( que,(d[edge[0]] , edge[0]) )
        w.append(d)
    for i in range(n-1):
        for j in range(i+1,n):
            for k in range(n):
                if i == k or j == k:
                    continue
                if w[i][j] < a[i][j]:
                    print(-1)
                    return
                if w[i][k] + w[k][j] == w[i][j]:
                    ans -= w[i][j]
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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
    w = []
    for i in range(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 d[edge[0]] > d[v] + edge[1]:
                    d[edge[0]] = d[v] + edge[1]
                    heappush( que,(d[edge[0]] , edge[0]) )
        w.append(d)
    for i in range(n-1):
        for j in range(i+1,n):
            for k in range(n):
                if i == k or j == k:
                    continue
                if w[i][k] + w[k][j] > w[i][j]:
                    continue
                if w[i][k] + w[k][j] == w[i][j]:
                    ans -= w[i][j]
                if w[i][k] + w[k][j] < w[i][j]:
                    print(-1)
                    return
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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
    w = []
    for i in range(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 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
        w.append(d)
    for i in range(n-1):
        for j in range(i+1,n):
            for k in range(n):
                if i == k or j == k:
                    continue
                if w[i][k] + w[k][j] == w[i][j]:
                    ans -= w[i][j]
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

dd = [[-1] * n for _ in range(n)]

def dijkstra(edges, s):
    global dd
    hq = []
    d = dd[s]
    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: Wrong Answer

Solution code:
print("-1")

Submission status: Wrong Answer

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, ans

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

#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, minus = warshall_floyd(B)
#print(cost, minus, A)

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


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

print(int(ans))

Submission status: Wrong Answer

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])
    th = np.sum(sorted(costs)[:2])
    result = 0
    for cost in costs:
        if cost < th:
            result += cost
    print(result)

Submission status: Wrong Answer

Solution code:
def warshall_floyd(d,ans):
    p = ans
    for k in range(n):
        for i in range(n):
            for j in range(n):
                flag = True
                if i == k or j == k:
                    continue
                if d[i][j] > d[i][k] + d[k][j]:
                    print(-1)
                    exit()
                elif flag and d[i][j] == d[i][k] + d[k][j]:
                    p -= d[i][j]
                    flag = False
    return p

##############################
n = int(input())

d = [list(map(int,input().split())) for i in range(n)] 
ans = 0
for i in range(n):
    ans += sum(d[i])

print(warshall_floyd(d,ans)//2)