bzoj2330
#include <bits/stdc++.h>
#include <algorithm>
#define N 100100
using namespace std;
typedef long long ll;
struct node {
int to;
int val;
int next;
};
node edge[N * 5];
int head[N];
int mp[N];
int d[N];
int v[N];
int cnt;
void init() {
memset(head, -1, sizeof(head));
cnt = 1;
}
void edgeadd(int from, int to, int val) {
edge[cnt].to = to;
edge[cnt].val = val;
edge[cnt].next = head[from];
head[from] = cnt++;
}
int n, k;
int spfa() {
memset(d, -0x3f, sizeof(d));
queue<int> q;
q.push(n + 1);
d[n + 1] = 0;
v[n + 1] = 1;
mp[n + 1] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
v[u] = 0;
for (int i = head[u]; i != -1; i = edge[i].next) {
int to = edge[i].to;
if (d[u] + edge[i].val > d[to]) {
d[to] = d[u] + edge[i].val;
if (++mp[to] >= n) return 0;
if (!v[to]) {
v[to] = 1;
q.push(to);
}
}
}
}
return 1;
}
int main() {
scanf("%d%d", &n, &k);
init();
for (int i = 1; i <= k; i++) {
int Q;
scanf("%d", &Q);
int x, y;
scanf("%d%d", &x, &y);
if(Q==2||Q==4){
if(x==y){cout<<-1<<endl;
return 0;}
}
if (Q == 1) {
edgeadd(x, y, 0);
edgeadd(y, x, 0);
}
else if (Q == 2) { edgeadd(x, y, 1); }
else if (Q == 3) { edgeadd(y, x, 0); }
else if (Q == 4) { edgeadd(y, x, 1); }
else if (Q == 5) { edgeadd(x, y, 0); }
}
for (int i = n; i >= 1; i--) {
edgeadd(n + 1, i, 1);
}
if (spfa()) {
ll sum = 0;
for (int i = 1; i <= n; i++) {
sum += d[i];
}
printf("%lld\n", sum);
} else printf("-1\n");
}