#include<bits/stdc++.h>
using namespace std;
const int MAXN=100010;
struct node{
int X,A,B;
}p[MAXN];
int n,k;
int m[MAXN];
long long ans;
signed main(){
cin>>n>>k;
for(int i=1;i<=k;i++)
cin>>p[i].X>>p[i].A>>p[i].B;
for(int i=1;i<=n;i++)
m[i]=1;
for (int T=1;T<=200;T++){
for (int i=1;i<=k;i++){
int a=p[i].A;
int b=p[i].B;
int x=p[i].X;
if(x==1){
if(m[a]>m[b])m[b]=m[a];
else m[a]=m[b];
}
else if(x==2)
if(m[a]>=m[b])m[b]=m[a]+1;
else if(x==3)
if(m[a]<m[b])m[a]=m[b];
else if(x==4)
if(m[a]<=m[b])m[a]=m[b]+1;
else if(x==5)
if(m[a]>m[b])m[b]=m[a];
}
}
for (int i=1;i<=k;i++){
int a=p[i].A;
int b=p[i].B;
int x=p[i].X;
if(x==1&&m[a]>m[b]){
cout<<-1<<endl;
return 0;
}
else if(x==2&&m[a]>=m[b]){
cout<<-1<<endl;
return 0;
}
else if(x==3&&m[a]<m[b]){
cout<<-1<<endl;
return 0;
}
else if(x==4&&m[a]<=m[b]){
cout<<-1<<endl;
return 0;
}
else if(x==5&&m[a]>m[b]){
cout<<-1<<endl;
return 0;
}
}
for(int i=1;i<=n;i++)
ans+=m[i];
cout<<ans<<endl;
return 0;
}