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: «employeeai 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.
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: ai, bi and ci (1 ≤ ai, bi ≤ n, 0 ≤ 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 the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.
4 7 2 3 1 4 1 2 5 2 4 1 3 4 1 1 3 5
11
3 1 2 3 2 3 1 2 3 1 3
-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.
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<string>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
struct node
{
int q,id;
}p[1005];
int a[1005][1005],d[1005],n;
bool cmp(node a,node b)
{
return a.q>b.q;
}
int main()
{
int i,j,k,v;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++) for(j=1;j<=n;j++) a[i][j]=-1;
for(i=1;i<=n;i++)
{
scanf("%d",&p[i].q);
p[i].id=i;
}
sort(p+1,p+1+n,cmp);
for(i=1;i<=n;i++)
{
d[p[i].id]=i;
}
scanf("%d",&k);
while(k--)
{
scanf("%d%d%d",&i,&j,&v);
i=d[i],j=d[j];
if(a[i][j]==-1) a[i][j]=v;
else a[i][j]=min(a[i][j],v);
}
int flag=0,ans=0;
for(i=2;i<=n;i++)
{
v=10000000;
for(j=1;j<i;j++)
{
if(p[j].q>p[i].q&&a[j][i]!=-1)
v=min(v,a[j][i]);
}
if(v==10000000) flag=1;
ans+=v;
if(flag) break;
}
if(flag) ans=-1;
printf("%d\n",ans);
}
return 0;
}