Under construction

Still being built. Things may change

Weekend Trip Plan

Interview

Time limit1sMemory limit512 MB

Summary
Given a weighted graph and separate destination and lodging values at each location, find the maximum of w_a + w_b - dist(a, b) over all destination-lodging pairs.
Level

Medium6 of 10

Topics
Graph, Shortest path, Brute force, Implementation
Solved
No attempts yet

Problem

Youngseon wants to visit exactly one travel destination and one lodging over the weekend.

The region has nn key locations connected by bidirectional roads, each with a travel distance. Every location is reachable from every other location by road. Each destination and each lodging sits at one location, and no destination shares a location with a lodging.

Let waw_a be the expectation value of destination aa, wbw_b the expectation value of lodging bb, and dist(a,b)dist(a, b) the shortest road distance between them. The score of a plan is

score(a,b)=wa+wb−dist(a,b)score(a, b) = w_a + w_b - dist(a, b)

Choose the pair with the largest score and compute that maximum. The route between the two locations may pass through other destinations or lodgings.

Input

The first line contains the number of locations nn (2≤n≤10002 \le n \le 1000).

The next nn lines give an adjacency matrix. The jj-th number on the ii-th line, dijd_{ij}, is the road distance between location ii and location jj. A value of 00 means there is no direct road (0≤dij≤50000 \le d_{ij} \le 5000, dij=djid_{ij} = d_{ji}, dii=0d_{ii} = 0).

The next line contains the number of destinations pp and the number of lodgings qq (1≤p,q≤n1 \le p, q \le n, 2≤p+q≤n2 \le p + q \le n).

The next pp lines each give a destination location number and its expectation value. The following qq lines each give a lodging location number and its expectation value. Location numbers are between 11 and nn inclusive, and every expectation value is between 11 and 50005000 inclusive.

Output

Print the maximum value of wa+wb−dist(a,b)w_a + w_b - dist(a, b) over all destination and lodging pairs. If every pair scores a negative value, print the largest (closest to zero) of them.

Examples1

  1. Example 1

    Input
    6
    0 5 0 1 0 0
    5 0 3 0 0 5
    0 3 0 0 0 2
    1 0 0 0 100 0
    0 0 0 100 0 3
    0 5 2 0 3 0
    2 2
    3 10
    6 11
    1 10
    4 11
    
    Expected output
    12