import sys


# Class to represent, read and solve a problem instance
class Problem:
    # Parsing of instance file
    def __init__(self, file_name):
        with open(file_name, "r") as f:
            lines = f.readlines()
        self.nb_cities, self.nb_items = map(int, lines[0].split()[1:])
        self.cost = []
        for line in lines[1 : 1 + self.nb_cities]:
            self.cost.append([int(i) for i in line.split()])
        self.items = []
        for line in lines[1 + self.nb_cities :]:
            self.items.append([int(i) for i in line.split()])

    def check(self, sol):
        if max(sol.indexes) >= self.nb_cities:
            print("City index too large", file=sys.stderr)
            return None
        if min(sol.indexes) < 0:
            print("Negative city index", file=sys.stderr)
            return None
        if len(sol.indexes) != len(set(sol.indexes)):
            print("Redundant city index", file=sys.stderr)
            return None
        cost = self.cost[sol.indexes[-1]][sol.indexes[0]]
        for i in range(len(sol.indexes) - 1):
            cost += self.cost[sol.indexes[i]][sol.indexes[i + 1]]
        for i in range(self.nb_items):
            if not any(self.items[i][j] >= 0 for j in sol.indexes):
                print("Some articles were not purchased", file=sys.stderr)
                return None
            cost += min(self.items[i][j] for j in sol.indexes if self.items[i][j] >= 0)
        return cost


# Class to represent a solution and write it in a file
class Solution:
    def __init__(self, file_name):
        with open(file_name, "r") as f:
            lines = f.readlines()
        self.indexes = [*map(int, lines[0].split())]


if __name__ == "__main__":
    try:
        instance_file_name = sys.argv[1]
        solution_file_name = sys.argv[2]
        p = Problem(instance_file_name)
        s = Solution(solution_file_name)
        res = p.check(s)
        if res is not None:
            print(f"Valid solution with cost {res}", file=sys.stderr)
            print(res)
        else:
            print("NA")
    except:
        print("Error while parsing instance of solution files", file=sys.stderr)
        print("NA")
