#include<bits/stdc++.h>
using namespace std;
const int N=100010;
int n,m;
int h[N],e[N*3],ne[N*3],w[N*3],idx;
long long dist[N];
int cnt[N];
bool st[N];
inline void add(int a,int b,int c){
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
bool spfa(){
memset(dist ,-0x3f,sizeof dist);
dist[0]=0;
stack<int> q;
q.push(0);
st[0]=1;
while(q.size()){
auto t=q.top();q.pop();
st[t]=0;
for(int i=h[t];~i;i=ne[i]){
int j=e[i];
if(dist[j]<dist[t]+w[i]){
dist[j]=dist[t]+w[i];
cnt[j]=cnt[t]+1;
if(cnt[j]>=n+1){
return 0;
}
if(!st[j]){
st[j]=1;
q.push(j);
}
}
}
}
return 1;
}
int main(){
scanf("%d%d",&n,&m);
memset(h,-1,sizeof h);
for(int i=1;i<=m;i++){
int x,a,b;
scanf("%d%d%d",&x,&a,&b);
if(x==1){
add(b,a,0);add(a,b,0);
}
else if(x==2){
add(a,b,1);
}
else if(x==3){
add(b,a,0);
}
else if(x==4){
add(b,a,1);
}
else if(x==5){
add(a,b,0);
}
}
for(int i=1;i<=n;i++) add(0,i,1);
if(!spfa()){
cout<<-1<<endl;
}
else {
long long res=0;
for(int i=1;i<=n;i++){
res+=dist[i];
}
printf("%lld",res);
}
return 0;
}