1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
#include<bits/stdc++.h>
using namespace std;
//a>=b -> dist[a] >= dist[b]
//a>b -> dist[a] >= dist[b] + 1
// 这样的等式,可以知道
//a >b , b> c, a<c ,是矛盾的,因为
/*
dist[a] = dist[b] + 1
dist[b] = dist[c] + 1
dist[a] = dist[c] -1 , 这个明显矛盾
*/
#define INFO pair<int,int>
// unordered_map<int,vector<INFO>> path;
int n,m;
const int MAXN = 1e5+100,MAXM = 3e6+300;
struct Edge{
int to,w,next;
}listNode[MAXM];
int head[MAXM], id;
void add(int u,int v, int w) {
++id;
//相当于 ListNode * p = new ListNode(id)
listNode[id].to = v,
listNode[id].w = w;
listNode[id].next = head[u];
head[u] = id;
}
long long dist[MAXN] ;
int cnt[MAXN];
bool state[MAXN];
bool spfa(int u) {
deque<int> stk;
stk.push_back(u);
//我们求出最短路径
memset(dist,-0x3f,sizeof dist);
dist[u] = 0;
while(stk.size()) {
int u = stk.back();stk.pop_back();
state[u] = 0;
for(int j = head[u];j; j = listNode[j].next) {
int v = listNode[j].to, w = listNode[j].w;
if(dist[v] < dist[u] + w) {
dist[v] = dist[u] + w;
cnt[v] = cnt[u] +1;
if(cnt[v] >= 1+ n) return false;
if(!state[v]) {
state[v] = 1;
stk.push_back(v);
}
}
}
}
return true;
}
int main()
{
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
else if(X==2) add(a,b,1); //B>=A+1 , a -> 1 -> b
else if(X==3) add(b,a,0); //a>=b
else if(X== 4) add(b,a,1); //a>=b+1
else add(a,b,0); //b>=a
}
for(int i=1;i<=n;++i) add(0,i,1); // a[i] >= dist[0] + 1
if(spfa(0) == 0) puts("-1");
else {
long long res= 0;
for(int i=1;i<=n;++i) res += dist[i];
cout << res <<endl;
}
return 0;
}
|