Problem:
Score : 400 points

Problem Statement

Joisino the magical girl has decided to turn every single digit that exists on this world into 1.

Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).

She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).

You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:

If A_{i,j}≠-1, the square contains a digit A_{i,j}.

If A_{i,j}=-1, the square does not contain a digit.

Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.

Constraints

1≤H,W≤200

1≤c_{i,j}≤10^3 (i≠j)

c_{i,j}=0 (i=j)

-1≤A_{i,j}≤9

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}

Output

Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.

Sample Input 1

2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

Sample Output 1

12

To turn a single 8 into 1, it is optimal to first turn 8 into 4, then turn 4 into 9, and finally turn 9 into 1, costing 6 MP.

The wall contains two 8s, so the minimum total MP required is 6×2=12.

Sample Input 2

5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

3 5
0 4 3 6 2 7 2 5 3 3
4 0 5 3 7 5 3 7 2 7
5 7 0 7 2 9 3 2 9 1
3 6 2 0 2 4 6 4 2 3
3 5 7 4 0 6 9 7 6 7
9 8 5 2 2 0 4 7 6 5
5 4 6 3 2 3 0 5 4 3
3 6 2 3 4 2 4 0 8 9
4 6 5 4 3 5 3 2 0 8
2 1 3 4 5 7 8 6 4 0
3 5 2 6 1
2 5 3 2 1
6 9 2 5 6

Sample Output 3

47

Solution in Java8 (OpenJDK 1.8.0) (judge verdict: Accepted)

import java.io.InputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {

  public static void main(String[] args) {
    solve(System.in, System.out);
  }

  static void solve(InputStream is, PrintStream os) {
    Scanner sc = new Scanner(is);

    /* read */
    int h = sc.nextInt();
    int w = sc.nextInt();

    int[][] c = new int[10][10];
    for (int j = 0; j < 10; j++) {
      for (int i = 0; i < 10; i++) {
        c[j][i] = sc.nextInt();
      }
    }

    Graph<Integer> graph = new AdjacencyMatrixGridPointGraph(10, c);
    Graph.Query<Integer> query = graph.query();

    long ans = 0;
    for (int j = 0; j < h; j++) {
      for (int i = 0; i < w; i++) {
        int a = sc.nextInt();
        if (a < 0) {
          continue;
        }
        ans += query.shortestPath(a, 1).getWeight();
      }
    }
    os.println(ans);
  }

//  private static int[] warshallFloyd(int[][] graph) {
//    for (int i = 0; i < 10; i++) { // relay point
//      for (int s = 0; s < 10; s++) {
//        for (int t = 0; t < 10; t++) {
//          graph[s][t] = Math.min(graph[s][t], graph[s][i] + graph[i][t]);
//        }
//      }
//    }
//    int[] d = new int[10];
//    for (int s = 0; s < 10; s++) {
//      d[s] = graph[s][1];
//    }
//    return d;
//  }
//
//  private static int[] dijkstraFrom1(int[][] graph) {
//    int[] t = new int[10];
//    for (int s = 0; s < 10; s++) {
//      t[s] = dijkstra(s, 1, graph);
//    }
//    return t;
//  }
//
//  private static int dijkstra(int start, int target, int[][] graph) {
//    int[] d = new int[10];
//    for (int i = 0; i < 10; i++) {
//      d[i] = Integer.MAX_VALUE;
//    }
//    d[start] = 0;
//    Queue<Integer> queue = new PriorityQueue<>(Comparator.comparingInt(i -> d[i]));
//    queue.add(start);
//    while (!queue.isEmpty()) {
//      int u = queue.remove();
//      for (int v = 0; v < 10; v++) {
//        int distance = d[u] + graph[u][v];
//        if (distance < d[v]) {
//          d[v] = distance;
//          queue.add(v);
//        }
//      }
//    }
//    return d[target];
//  }


  private static class GridPointEncoder implements Encoder<GridPoint> {

    public GridPointEncoder(int h, int w) {
      this.h = h;
      this.w = w;
    }

    private final int h;
    private final int w;

    @Override
    public int num() {
      return w * h;
    }

    @Override
    public int encode(GridPoint from) {
      return w * from.r + from.c;
    }

    @Override
    public GridPoint decode(int from) {
      return new GridPoint(from / w, from % w);
    }
  }

  private static class GridPoint implements Encoded<GridPoint> {

    private final int r;
    private final int c;

    public GridPoint(int r, int c) {
      this.r = r;
      this.c = c;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }
      GridPoint gridPoint = (GridPoint) o;
      return r == gridPoint.r &&
          c == gridPoint.c;
    }

    @Override
    public int hashCode() {
      return Objects.hash(r, c);
    }
  }

  private static class VerticalHorizontalNeighborGridPointGraph extends GridPointGraph {

    private final boolean[][] grid;

    private final Predicate<GridPoint> predicate = this::predicate;
    private int[][] moves = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    public VerticalHorizontalNeighborGridPointGraph(int h, int w, boolean[][] grid) {
      super(h, w);
      this.grid = grid;
    }

    private boolean predicate(GridPoint p) {
      if (p.r < 0 || h <= p.r) {
        return false;
      }
      if (p.c < 0 || w <= p.c) {
        return false;
      }
      return grid[p.r][p.c];
    }

    private Set<Edge<GridPoint>> neighbors(GridPoint from) {

      return Arrays.stream(moves)
          .map(move -> new GridPoint(from.r + move[0], from.c + move[1]))
          .filter(predicate)
          .map(to -> new ConstantWeightEdge<>(from, to))
          .collect(Collectors.toSet());
    }

    @Override
    public Set<Edge<GridPoint>> getEdges(GridPoint from) {
      if (predicate.test(from)) {
        return neighbors(from);
      } else {
        return Collections.emptySet();
      }
    }
  }

  private static class AdjacencyMatrixGridPointGraph extends IntVertexGraph {

    private final Set<Integer> vertexes = new HashSet<>();

    private final int n;
    private final int[][] matrix;

    public AdjacencyMatrixGridPointGraph(int n, int[][] matrix) {
      this.n = n;
      this.matrix = matrix;
      IntStream.range(0, n).forEach(vertexes::add);
    }

    @Override
    public Set<Integer> getVertexes() {
      return vertexes;
    }

    @Override
    public Set<Edge<Integer>> getEdges(Integer from) {
      return IntStream.range(0, n).mapToObj(to -> new Edge<>(from, to, matrix[from][to]))
          .collect(Collectors.toSet());
    }
  }

  private static class AdjacencyListGridPointGraph extends IntVertexGraph {

    private final Set<Integer> vertexes = new HashSet<>();

    private final int n;
    private final List<Set<Edge<Integer>>> lists;

    public AdjacencyListGridPointGraph(int n, Set<Integer>[] lists) {
      this.n = n;
      this.lists = IntStream.range(0, n)
          .mapToObj(from -> lists[from].stream()
              .map(to -> new Edge<>(from, to, 1L)).collect(Collectors.toSet()))
          .collect(Collectors.toList());
      IntStream.range(0, n).forEach(vertexes::add);
    }

    @Override
    public Set<Integer> getVertexes() {
      return vertexes;
    }

    @Override
    public Set<Edge<Integer>> getEdges(Integer from) {
      return lists.get(from);
    }
  }


  private static abstract class GridPointGraph extends EncodedGraph<GridPoint> {

    public GridPointGraph(int h, int w) {
      super(new GridPointEncoder(h, w));
      this.h = h;
      this.w = w;

      for (int r = 0; r < h; r++) {
        for (int c = 0; c < w; c++) {
          nodes.add(new GridPoint(r, c));
        }
      }
    }

    protected final int h;
    protected final int w;

    protected final Set<GridPoint> nodes = new HashSet<>();

    @Override
    public Set<GridPoint> getVertexes() {
      return nodes;
    }
  }

  private static interface Encoded<E extends Encoded> {

  }

  private static interface Encoder<E extends Encoded> {

    int num();

    int encode(E from);

    E decode(int from);
  }

  private static abstract class EncodedGraph<V extends Encoded<V>> implements Graph<V> {

    public EncodedGraph(Encoder<V> encoder) {
      this.encoder = encoder;
      this.delegate = new IntVertexGraph() {
        @Override
        public Set<Integer> getVertexes() {
          return EncodedGraph.this.getVertexes().stream()
              .map(encoder::encode)
              .collect(Collectors.toSet());
        }

        @Override
        public Set<Edge<Integer>> getEdges(Integer from) {
          return EncodedGraph.this.getEdges(encoder.decode(from)).stream()
              .map(e -> new Edge<>(encoder.encode(e.getFrom()), encoder.encode(e.getTo()),
                  e.getWeight()))
              .collect(Collectors.toSet());
        }
      };
    }

    private final Encoder<V> encoder;
    private final IntVertexGraph delegate;

    @Override
    public Query<V> query() {
      return new Query<V>() {

        private final Query<Integer> delegate = EncodedGraph.this.delegate.query();

        @Override
        public VertexPath<V> shortestPath(V begin, V end) {
          VertexPath<Integer> path = delegate
              .shortestPath(encoder.encode(begin), encoder.encode(end));
          if (path == null) {
            return null;
          }
          return new EfficientVertexPath<>(encoder.decode(path.getBegin()),
              encoder.decode(path.getEnd()), path.getWeight());
        }
      };
    }
  }

  private static abstract class IntVertexGraph implements Graph<Integer> {

    private static class QueueQuery {

      private final Queue<VertexPath<Integer>> queue;
      private final Graph<Integer> graph;

      protected QueueQuery(Graph<Integer> graph, Queue<VertexPath<Integer>> queue) {
        this.graph = graph;
        this.queue = queue;
      }

      VertexPath<Integer> path(Integer begin, Integer end) {
        Set<Integer> visited = new HashSet<>();
        queue.add(new EfficientVertexPath<>(begin));
        visited.add(begin);

        while (!queue.isEmpty()) {
          VertexPath<Integer> path = queue.remove();
          Integer head = path.getEnd();

          Set<Edge<Integer>> candidates = graph.getEdges(head);
          if (head.equals(end)) {
            return path;
          }
          for (Edge<Integer> c : candidates) {
            if (!visited.contains(c.getTo())) {
              VertexPath<Integer> p = new EfficientVertexPath<>(path, c);
              queue.add(p);
              visited.add(c.getTo());
            }
          }
        }
        return null;
      }
    }

    private static class DijkstraQuery implements Query<Integer> {

      final Graph<Integer> graph;

      private DijkstraQuery(Graph<Integer> graph) {
        this.graph = graph;
      }

      @Override
      public VertexPath<Integer> shortestPath(Integer begin, Integer end) {
        QueueQuery delegate = new QueueQuery(graph,
            new PriorityQueue<>(Comparator.comparingLong(VertexPath::getWeight)));
        return delegate.path(begin, end);
      }
    }

    private static class BfsQuery implements Query<Integer> {

      final Graph<Integer> graph;

      private BfsQuery(Graph<Integer> graph) {
        this.graph = graph;
      }

      @Override
      public VertexPath<Integer> shortestPath(Integer begin, Integer end) {
        QueueQuery delegate = new QueueQuery(graph, new ArrayDeque<>());
        return delegate.path(begin, end);
      }
    }

    private static class WarshallFloydQuery implements Query<Integer> {

      private final Graph<Integer> graph;

      private VertexPath<Integer>[][] shortest;

      private WarshallFloydQuery(Graph<Integer> graph) {
        this.graph = graph;

        Set<Integer> nodes = graph.getVertexes();

        shortest = new VertexPath[nodes.size()][nodes.size()];

        for (int from : nodes) {
          Set<Edge<Integer>> edges = graph.getEdges(from);
          for (Edge<Integer> e : edges) {
            shortest[e.getFrom()][e.getTo()] = new EfficientVertexPath<>(e);
          }
          shortest[from][from] = new EfficientVertexPath<>(from);
        }

        for (int relay : nodes) {
          for (int from : nodes) {
            for (int dest : nodes) {
              VertexPath<Integer> pathA = shortest[from][relay];
              VertexPath<Integer> pathB = shortest[relay][dest];
              if (pathA != null && pathB != null) {
                VertexPath<Integer> path = pathA.append(pathB);
                if (shortest[from][dest] == null || path.getWeight() < shortest[from][dest]
                    .getWeight()) {
                  shortest[from][dest] = path;
                }
              }
            }
          }
        }
      }

      @Override
      public VertexPath<Integer> shortestPath(Integer begin, Integer end) {
        return shortest[begin][end];
      }
    }

    @Override
    public Query<Integer> query() {
      return new WarshallFloydQuery(this);
      // return new BfsQuery(this);
    }
  }

  private static interface Graph<V> {

    static class Edge<V> {

      public Edge(V from, V to, long weight) {
        this.from = from;
        this.to = to;
        this.weight = weight;
      }

      private final V from;

      private final V to;
      private final long weight;


      V getFrom() {
        return from;
      }

      V getTo() {
        return to;
      }

      long getWeight() {
        return weight;
      }
    }

    static class ConstantWeightEdge<V> extends Edge<V> {

      public ConstantWeightEdge(V from, V to) {
        super(from, to, 1);
      }
    }

    Set<V> getVertexes();

    Set<Edge<V>> getEdges(V from);

    static interface VertexPath<V> {

      V getBegin();

      V getEnd();

      long getWeight();

      VertexPath<V> append(VertexPath<V> other);
    }

    Query<V> query();

    static interface Query<V> {

      VertexPath<V> shortestPath(V begin, V end);
    }

    static class EfficientVertexPath<V> implements VertexPath<V> {

      final V begin;
      final V end;
      final long weight;

      public EfficientVertexPath(V begin) {
        this.begin = begin;
        this.end = begin;
        this.weight = 0;
      }

      public EfficientVertexPath(V begin, V end, long weight) {
        this.begin = begin;
        this.end = end;
        this.weight = weight;
      }

      public EfficientVertexPath(Edge<V> edge) {
        this.begin = edge.getFrom();
        this.end = edge.getTo();
        this.weight = edge.getWeight();
      }

      public EfficientVertexPath(VertexPath<V> path, Edge<V> append) {
        this.begin = path.getBegin();
        if (!path.getEnd().equals(append.getFrom())) {
          throw new IllegalStateException("not correct edge.");
        }
        this.end = append.getTo();
        this.weight = path.getWeight() + append.getWeight();
      }

      public EfficientVertexPath(VertexPath<V> pathA, VertexPath<V> pathB) {
        this.begin = pathA.getBegin();
        if (!pathA.getEnd().equals(pathB.getBegin())) {
          throw new IllegalStateException("not correct edge.");
        }
        this.end = pathB.getEnd();
        this.weight = pathA.getWeight() + pathB.getWeight();
      }

      @Override
      public V getBegin() {
        return begin;
      }

      @Override
      public V getEnd() {
        return end;
      }

      @Override
      public long getWeight() {
        return weight;
      }

      @Override
      public VertexPath<V> append(VertexPath<V> other) {
        return new EfficientVertexPath<>(this, other);
      }

      @Override
      public boolean equals(Object o) {
        if (this == o) {
          return true;
        }
        if (o == null || getClass() != o.getClass()) {
          return false;
        }
        EfficientVertexPath<?> that = (EfficientVertexPath<?>) o;
        return weight == that.weight &&
            Objects.equals(begin, that.begin) &&
            Objects.equals(end, that.end);
      }

      @Override
      public int hashCode() {
        return Objects.hash(begin, end, weight);
      }
    }
  }

  private static class Scanner {

    private final InputStream is;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    Scanner(InputStream is) {
      this.is = is;
    }

    private boolean hasNextByte() {
      if (ptr < buflen) {
        return true;
      } else {
        ptr = 0;
        try {
          buflen = is.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (buflen <= 0) {
          return false;
        }
      }
      return true;
    }

    private int readByte() {
      if (hasNextByte()) {
        return buffer[ptr++];
      } else {
        return -1;
      }
    }

    private static boolean isPrintableChar(int c) {
      return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) {
        ptr++;
      }
      return hasNextByte();
    }

    public String next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      StringBuilder sb = new StringBuilder();
      int b = readByte();
      while (isPrintableChar(b)) {
        sb.appendCodePoint(b);
        b = readByte();
      }
      return sb.toString();
    }

    public long nextLong() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      long n = 0;
      boolean minus = false;
      int b = readByte();
      if (b == '-') {
        minus = true;
        b = readByte();
      }
      if (b < '0' || '9' < b) {
        throw new NumberFormatException();
      }
      while (true) {
        if ('0' <= b && b <= '9') {
          n *= 10;
          n += b - '0';
        } else if (b == -1 || !isPrintableChar(b)) {
          return minus ? -n : n;
        } else {
          throw new NumberFormatException();
        }
        b = readByte();
      }
    }

    public int nextInt() {
      long nl = nextLong();
      if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) {
        throw new NumberFormatException();
      }
      return (int) nl;
    }

    public double nextDouble() {
      return Double.parseDouble(next());
    }
  }
}