You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.6 KiB

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 100010, M = 300010;
int n, m;
int h[N], e[M], w[M], ne[M], idx;
int q[N], cnt[N];
LL dist[N];
bool st[N];
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
bool spfa() {
int hh = 0, tt = -1;
for (int i = 1; i <= n; i++) {
q[++tt] = i;
st[i] = true;
dist[i] = 1;
}
while (hh <= tt) {
int u = q[hh++];
st[u] = false;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (dist[v] < dist[u] + w[i]) {
dist[v] = dist[u] + w[i];
cnt[v] = cnt[u] + 1;
if (cnt[v] >= n) return true;
if (!st[v]) {
q[++tt] = v;
st[v] = true;
}
}
}
}
return false;
}
int main() {
// 最小值最长路,i->j,dj>=di+c
memset(h, -1, sizeof h);
cin >> n >> m;
while (m--) {
int x, a, b;
cin >> x >> a >> b;
if (x == 1) add(a, b, 0), add(b, a, 0); // A=B,A>=B,B>=A
if (x == 2) add(a, b, 1); // A<B,B-1>=A
if (x == 3) add(b, a, 0); // A>=B,B->A
if (x == 4) add(b, a, 1); // A>B,A>=B+1,B->A
if (x == 5) add(a, b, 0); // A<=B,B>=A,A->B
}
if (spfa())
puts("-1");
else {
LL res = 0;
for (int i = 1; i <= n; i++) res += dist[i];
printf("%lld\n", res);
}
return 0;
}