C. MST problem
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

There is a graph $$$G$$$ with $$$A = \sum_{i=1}^{n} a_i$$$ vertices, numbered $$$1, 2, \ldots A$$$. For each $$$1 \leq i \leq n$$$, there are $$$a_i$$$ vertices with type $$$i$$$. The vertices numbered $$$(\sum_{j=1}^{i-1} a_j) + r$$$ are of type $$$a_i$$$ for each $$$r \in \{1, 2, \ldots a_i\}$$$. That is, the first $$$a_1$$$ vertices have type $$$1$$$, the next $$$a_2$$$ vertices have type $$$2$$$, and so on.

The edges of the graph are described through $$$m$$$ 4-tuples. Each tuple is of the form $$$t \text{ } u \text{ } v \text{ } w$$$, where $$$t \in \{1,2\}$$$, and $$$u \neq v$$$:

  • If $$$t = 1$$$, then $$$1 \leq u, v \leq A$$$. There is an edge of weight $$$w$$$ between vertices numbered $$$u$$$ and $$$v$$$.
  • If $$$t = 2$$$, then $$$1\leq u, v \leq n$$$. For any pair of vertices $$$(x, y)$$$ of the graph where $$$x$$$ is of type $$$u$$$ and $$$y$$$ is of type $$$v$$$, there is an edge of weight $$$w$$$.

Please note that there might be multiple edges between the same pair of vertices in the graph.

Find the cost of the minimum spanning tree of the graph, or print $$$-1$$$ if the graph is disconnected.

Input

The first line contains two integers $$$n (1 \leq n \leq 10^5)$$$ and $$$m(1 \leq m \leq 2 \cdot 10^5$$$)

The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots a_n$$$, where $$$1 \leq a_i \leq 10^9$$$ and the sum of all $$$a_i$$$ does not exceed $$$10^9$$$.

Each of the next $$$m$$$ lines contains a $$$4-$$$tuple, of the form $$$t \text{ } u \text{ } v \text{ } w$$$

Output

Print the cost of the minimum spanning tree of the graph. If the graph is disconnected, print $$$-1$$$ instead.

Example
Input
3 4
2 3 1
2 1 2 5
2 2 3 7
1 1 6 3
1 1 2 10
Output
23
Note

The graph $$$G$$$ is the following:

The minimum spanning tree is the following: