//rename file to Main.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); long ans = 0; long flippedAns = 0; long[][] A = readMatrix(input); int l = Integer.parseInt(input.readLine()); for (int k = 0; k < l; k++) { String str = input.readLine(); StringTokenizer data = new StringTokenizer(str); int i = Integer.parseInt(data.nextToken())-1; int j = Integer.parseInt(data.nextToken())-1; if (ans != -1) { try { ans += A[i][j]; } catch (ArrayIndexOutOfBoundsException e) { ans = -1; } } if (flippedAns != -1) { try { flippedAns += A[j][i]; } catch (ArrayIndexOutOfBoundsException e) { flippedAns = -1; } } } System.out.println(Math.max(ans, flippedAns)); } private static long[][] readMatrix(BufferedReader input) throws IOException { String str = input.readLine(); StringTokenizer data = new StringTokenizer(str); int n = Integer.parseInt(data.nextToken()); int m = Integer.parseInt(data.nextToken()); long[][] A = new long[n][m]; for (int i = 0; i < n; i++) { str = input.readLine(); data = new StringTokenizer(str); for (int j = 0; j < m; j++) { A[i][j] = Long.parseLong(data.nextToken()); } } return A; } }