#include <bits/stdc++.h>
using namespace std;
struct Graph{
struct Edge{
int next;
int to;
int weight;
} edges[10005];
int head[5005];
int edge_count;
Graph(){
edge_count = 0;
}
void add(int from,int to,int weight){
edges[++edge_count].next=head[from];
edges[edge_count].to=to;
edges[edge_count].weight=weight;
head[from]=edge_count;
}
void add_undirected(int from,int to,int weight){
add(from,to,weight);
add(to,from,weight);
}
};
int n,m;
Graph g;
int tot[5005];
int Dis[5005];
int Vis[5005];
bool spfa(int start=0){
int u,v;
queue<int> q;
q.push(start);
Dis[start]=0;
Vis[start]=1;
while(!q.empty()){
u=q.front();
Vis[u]=0;
q.pop();
for(int j=g.head[u];j;j=g.edges[j].next){
v=g.edges[j].to;
if(Dis[v]>Dis[u]+g.edges[j].weight){
Dis[v]=Dis[u]+g.edges[j].weight;
if(!Vis[v]){
Vis[v]=1;
tot[v]++;
if(tot[v]==n+1){
return false;
}
q.push(v);
}
}
}
}
return true;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
for(int i=0;i<m;i++){
int op,x,y;
cin>>op>>x>>y;
switch(op){
case 1:
g.add_undirected(x,y,0);
break;
case 2:
g.add(x,y,1);
break;
case 3:
g.add(y,x,0);
break;
case 4:
g.add(y,x,1);
break;
case 5:
g.add(x,y,0);
break;
}
}
for(int i=1;i<=n;i++){
g.add(n+1,i,1);
}
for(int i=0;i<n;i++)Dis[i]=0;
bool res = spfa();
if(!res){
cout<<"-1"<<endl;
}
else{
int ans=0;
for(int i=1;i<=n;i++){
ans+=Dis[i];
}
cout<<ans<<endl;
}
return 0;
}