#P17B. Hierarchy

Hierarchy

题目描述

nn 的公司有 nn 个员工,每个员工 ii 有一个初始的权值 qiq_i ,每一个员工有且只有一个上司。 有 mm 条申请,每个申请由三个数 aia_ibib_icic_i 构成,代表将 aia_i 任命为 bib_i 的上司所需要的花费为cic_i,同时必须保证 qai>qbiq_{a_i}>q_{b_i}。试求使每个员工(顶头上司除外)都有且只有一个上司所花费的最小代价。

输入格式

第一行 nn,第二行 nn 个数表示 qiq_i,第三行 mm,之后 mm 行每行三个数表示aia_ibib_icic_i

输出格式

一个整数表示最小代价,若无解则输出 -1

说明/提示

数据规模与约定

1n1031 \le n \le 10^30m1040 \le m \le 10^4, 0qi1060 \le q_i \le 10^60ci1060 \le c_i \le 10^61ai,bin1 \le a_i,b_i \le n

题目描述

Nick's company employed n n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m m applications written in the following form: «employee ai a_{i} is ready to become a supervisor of employee bi b_{i} at extra cost ci c_{i} ». The qualification qj q_{j} of each employee is known, and for each application the following is true: qai>qbi q_{ai}>q_{bi} .

Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.

输入格式

The first input line contains integer n n ( 1<=n<=1000 1<=n<=1000 ) — amount of employees in the company. The following line contains n n space-separated numbers qj q_{j} ( 0<=qj<=106 0<=q_{j}<=10^{6} )— the employees' qualifications. The following line contains number m m ( 0<=m<=10000 0<=m<=10000 ) — amount of received applications. The following m m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai a_{i} , bi b_{i} and ci c_{i} ( 1<=ai,bi<=n 1<=a_{i},b_{i}<=n , 0<=ci<=106 0<=c_{i}<=10^{6} ). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai>qbi q_{ai}>q_{bi} .

输出格式

Output the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.

样例 #1

样例输入 #1

4
7 2 3 1
4
1 2 5
2 4 1
3 4 1
1 3 5

样例输出 #1

11

样例 #2

样例输入 #2

3
1 2 3
2
3 1 2
3 1 3

样例输出 #2

-1

提示

In the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1.