#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 100010, M = 600010;
int n, m;
int h[N], hs[N], e[M], w[M], ne[M], idx;
int dfn[N], low[N], scc[N], sz[N], dfncnt, sc;
bool stk[N];
stack<int> St;
int dist[N];
void add(int h[], int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
void tarjan(int u) {
dfn[u] = low[u] = ++dfncnt;
St.push(u);
stk[u] = true;
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (!dfn[j]) {
tarjan(j);
low[u] = min(low[u], low[j]);
} else if (stk[j]) low[u] = min(low[u], dfn[j]);
}
if (dfn[u] == low[u]) {
int y;
++sc;
do {
y = St.top();
St.pop();
stk[y] = false;
scc[y] = sc;
sz[sc]++;
} while (y != u);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
memset(h, -1, sizeof h);
memset(hs, -1, sizeof hs);
cin >> n >> m;
while (m--) {
int t, a, b;
cin >> t >> a >> b;
if (t == 1) add(h, a, b, 0), add(h, b, a, 0);
else if (t == 2) add(h, a, b, 1);
else if (t == 3) add(h, b, a, 0);
else if (t == 4) add(h, b, a, 1);
else add(h, a, b, 0);
}
for (int i = 1; i <= n; i++) add(h, 0, i, 1);
tarjan(0);
bool ok = true;
for (int i = 0; i <= n; i++) {
for (int j = h[i]; j != -1; j = ne[j]) {
int k = e[j];
int a = scc[i], b = scc[k];
if (a == b) {
if (w[j] > 0) {
ok = false;
break;
}
} else add(hs, a, b, w[j]);
}
if (!ok) break;
}
if (!ok) cout << -1 << endl;
else {
for (int i = sc; i; i--) {
for (int j = hs[i]; j != -1; j = ne[j]) {
int k = e[j];
dist[k] = max(dist[k], dist[i] + w[j]);
}
}
LL res = 0;
for (int i = 1; i <= n; i++) res += (LL)dist[i] * sz[i];
cout << res << endl;
}
return 0;
}