#include <bits/stdc++.h>
using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

#define fastio() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define test() int t;cin>>t;for(int test=1;test<=t;test++)
#define pb push_back
#define nl cout<<"\n"
#define F first
#define S second
#define all(x) x.begin(),x.end()

template<class C> void min_self( C &a, C b ){ a = min(a,b); }
template<class C> void max_self( C &a, C b ){ a = max(a,b); }

const ll MOD = 1000000007;
ll mod( ll n, ll m=MOD ){ n%=m,n+=m,n%=m;return n; }

const int MAXN = 1e5+5;
const int LOGN = 21;
const ll INF = 1e14;
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};


class DSU
{
public:
    vector<int>rt,sz;
    int components;
    DSU( int n )
    {
        rt.resize(n+5);
        sz.resize(n+5);
        components = n;
        for(int i=0;i<n;i++)
        {
            rt[i] = i;
            sz[i] = 1;
        }
    }
    int get_components()
    {
        return components;
    }
    int root( int x )
    {
        while( x != rt[x] )
        {
            rt[x] = rt[rt[x]];
            x = rt[x];
        }
        return x;
    }
    void connect( int x, int y )
    {
        int r1 = root(x);
        int r2 = root(y);
        if( r1 == r2 )
            return;
        if( sz[r1] < sz[r2] )
            swap(r1,r2);
        sz[r1] += sz[r2];
        rt[r2] = r1;
        components--;
    }
};


int main() 
{
    // #ifndef ONLINE_JUDGE
        // freopen("../input.txt", "r", stdin);
        // freopen("../output.txt", "w", stdout);
    // #endif
    // freopen("wormsort.in", "r", stdin);
    // freopen("wormsort.out", "w", stdout);
    fastio();

    int n,m;
    cin>>n>>m;
    vector<int>p(n);
    set<int>unmatched;
    DSU d(2*n);
    for(int i=0;i<n;i++)
    {
        cin>>p[i];
        p[i]--;
        if( p[i] != i )
        {
            d.connect(i+n,p[i]);
            unmatched.insert(i);
        }
    }

    vector<vector<int>>edges(m,vector<int>(3,0));
    for(int i=0;i<m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        u--,v--;
        edges.pb({w,u,v});
    }
    sort(all(edges),greater<vector<int>>());

    if( unmatched.empty() )
    {
        cout<<-1,nl;
        return 0;
    }

    for(int i=0;i<m;i++)
    {
        int w = edges[i][0], u = edges[i][1], v = edges[i][2];

        d.connect(u,v);
        if( d.root(u) == d.root(u+n) )
            unmatched.erase(u);
        if( d.root(v) == d.root(v+n) )
            unmatched.erase(v);

        for( auto x : unmatched )
        {
            if( d.root(x) == d.root(x+n) )
                unmatched.erase(x);
        }

        if( unmatched.empty() )
        {
            cout<<w,nl;
            return 0;
        }
    }


    cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
    return 0;
}