差分约束
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = 3e5 + 10;
int h[N], e[M], ne[M], w[M], idx;
bool st[N];
int cnt[N];
long long int dist[N];
int n, m;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
bool spfa()
{
int q[N], hh = -1, tt = 0;
memset(dist, -0x3f,sizeof dist);
q[0] = 0;
st[0] = true;
dist[0] = 0;
while (hh != tt)
{
int t = q[tt --];
st[t] = false;
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 true;
if (!st[j])
{
q[++ tt] = j;
st[j] = true;
}
}
}
}
return false;
}
int main(void)
{
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i ++)
{
int x, a, b;
cin >> x >> a >> b;
if (x == 1) add(a, b, 0), add(b, a, 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()) puts("-1");
else
{
long long int res = 0;
for (int i = 1; i <= n; i ++) res += dist[i];
printf("%lld\n", res);
}
return 0;
}