#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define N 300000
int i,j,k,n,m,t,fa[N+50],in[N+50];
ll dep[N+50],res=1e18;
bool sb[N+50];
vector<pair<int,int> > v[N+50],v2[N+50];
vector<tuple<int,int,int> > bian;
int find(int x){return (fa[x]==x)?x:fa[x]=find(fa[x]);}
int it;
ll s1[N+50],s2[N+50],f[N+50];
void dfs(int x,ll dep){
if(sb[x]){
if(it){
//cout<<"NMSL "<<s1[it]<<' '<<x<<' '<<dep-s2[it]<<endl;
v2[s1[it]].push_back({x,dep-s2[it]});
}
s1[++it]=x; s2[it]=dep;
}
for(auto [i,j]:v[x]){
dfs(i,dep+j);
}
if(sb[x])it--;
}
ll fuck(ll st,ll ed){
for(auto [i,j,k]:bian){
f[i]=f[j]=1e18;
}
priority_queue<pair<ll,ll> > q;
q.push({0,st});
while(!q.empty()){
auto [w,id]=q.top(); q.pop(); w=-w;
if(f[id]<=w)continue;
f[id]=w;
for(auto [i,j]:v2[id])if(f[i]>w+j){
q.push({-(w+j),i});
}
}
return f[ed];
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
cin>>n>>m;
for(i=1;i<=n;i++)fa[i]=i;
for(i=1;i<=m;i++){
int x,y,z;
cin>>x>>y>>z;
if(find(x)==find(y)){
v2[x].push_back({y,z});
bian.push_back({x,y,z});
sb[x]=sb[y]=1; continue;
}
//cout<<"nmsl "<<x<<' '<<y<<' '<<z<<endl;
fa[find(x)]=find(y);
v[x].push_back({y,z}); in[y]++;
}
for(i=1;i<=n;i++)if(!in[i]){
dfs(i,0);
}
int NMSL=0;
for(i=1;i<=n;i++){
NMSL+=v2[i].size();
}
if(NMSL.size()>5000||bian.size()>5000)return 1;
for(auto [l,r,w]:bian){
res=min(res,fuck(r,l)+w);
}
if(res>1e17)res=-1;
cout<<res;
}