Under construction

Still being built. Things may change

Find the MST for Grid

Time limit2sMemory limit512 MB

Summary
Given a grid graph whose edge weights come from four non-decreasing sequences, find the total weight of its minimum spanning tree.
Level

Hard8 of 10

Topics
Minimum spanning tree, Greedy, Sorting, Implementation
Solved
No attempts yet

Problem

Consider a grid graph: the vertices are lined up into a grid of HH rows by WW columns. Let us denote the vertex in the ii-th row and jj-th column as (i,j)(i, j).

To define the weights of the graph edges, we will consider four non-decreasing sequences, AA, BB, CC, and DD, consisting of H−1H-1, WW, HH, and W−1W-1 positive integers, respectively:

  • there is a bidirectional edge connecting vertices (i,j)(i, j) and (i+1,j)(i+1, j) of weight A_i+B_jA\_i + B\_j for all ii and jj such that 1≤i≤H−11 \le i \le H-1 and 1≤j≤W1 \le j \le W;
  • there is a bidirectional edge connecting vertices (i,j)(i, j) and (i,j+1)(i, j+1) of weight C_i+D_jC\_i + D\_j for all ii and jj such that 1≤i≤H1 \le i \le H and 1≤j≤W−11 \le j \le W-1;
  • the graph contains no other edges.

Find the total weight of the edges in the minimal spanning tree of this graph.

Input

The first line of input contains two positive integers HH and WW (2≤H,W≤1052 \le H, W \le 10^5).

The second line contains H−1H-1 integers A_iA\_i: the elements of the sequence AA.

The third line contains WW integers B_iB\_i: the elements of the sequence BB.

The fourth line contains HH integers C_iC\_i: the elements of the sequence CC.

The fifth line contains W−1W-1 integers D_iD\_i: the elements of the sequence DD.

It is guaranteed that A_i−1≤A_iA\_{i-1} \le A\_{i}, B_i−1≤B_iB\_{i-1} \le B\_{i}, C_i−1≤C_iC\_{i-1} \le C\_{i}, and D_i−1≤D_iD\_{i-1} \le D\_{i} for i>1i>1, and additionally, 1≤A_i,B_i,C_i,D_i≤1061 \le A\_i, B\_i, C\_i, D\_i \le 10^6.

Output

Print the total weight of the edges in the minimal spanning tree of the given graph. Note that the answer may not fit into a 32-bit integer.

Examples2

  1. Example 1

    Input
    2 3
    1
    1 3 6
    1 4
    1 2
    
    Expected output
    17
    
  2. Example 2

    Input
    4 3
    1 13 15
    3 6 11
    3 6 6 11
    9 17
    
    Expected output
    173