Algorithm


B. Hierarchy
time limit per test
2 seconds
memory limit per test
64 megabytes
input
standard input
output
standard output

Nick's company employed 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 applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai > qbi.

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

Input

The first input line contains integer n (1 ≤ n ≤ 1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0 ≤ qj ≤ 106)— the employees' qualifications. The following line contains number m (0 ≤ m ≤ 10000) — amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: aibi and ci (1 ≤ ai, bi ≤ n0 ≤ ci ≤ 106). 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.

Output

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

Examples
input
Copy
4
7 2 3 1
4
1 2 5
2 4 1
3 4 1
1 3 5
output
Copy
11
input
Copy
3
1 2 3
2
3 1 2
3 1 3
output
Copy
-1
Note

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.



 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include <cstdio>
#include <map>

int main(){

    long n; scanf("%ld", &n);
    for(long p = 0; p < n; p++){long x; scanf("%ld", &x);} //Irrelevant
    long m; scanf("%ld", &m);
    std::map<long, long> cost;
    while(m--){
        long x, y, c; scanf("%ld %ld %ld", &x, &y, &c);
        if(cost.count(y) > 0){cost[y] = (cost[y] < c) ? cost[y] : c;}
        else{cost[y] = c;}
    }

    if(cost.size() < n - 1){puts("-1"); return 0;}

    long long total(0);
    for(std::map<long, long>::iterator it = cost.begin(); it != cost.end(); it++){total += it->second;}
    printf("%lld\n", total);

    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
4
7 2 3 1
4
1 2 5
2 4 1
3 4 1
1 3 5

Output

x
+
cmd
11
Advertisements

Demonstration


Codeforces Solution-B. Hierarchy-Solution in C, C++, Java, Python

Previous
Codeforces solution 1080-B-B. Margarite and the best present codeforces solution
Next
CodeChef solution DETSCORE - Determine the Score CodeChef solution C,C+