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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include <map> #include <set> #include <ctime> #include <cmath> #include <queue> #include <stack> #include <deque> #include <bitset> #include <cctype> #include <cstdio> #include <vector> #include <utility> #include <cstdlib> #include <cstring> #include <sstream> #include <iostream> #include <algorithm> #define eps 1e-8 #define ms(i, val) memset(i, val, sizeof i) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> P; const int N = 3e5 + 5; const int M = 3e6 + 5; const int INF = 0x3f3f3f3f; const ll ll_max = 4557430888798830399; inline int read() { int res = 0; bool f = 0; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = 1; ch = getchar(); } while (ch <= '9' && ch >= '0') { res = (res << 3) + (res << 1) + ch - '0'; ch = getchar(); } return f ? (~ res + 1) : res; } struct edge { int u, v;ll w; int ne; } ed[M]; int cnt, n, m, head[N], tim[N]; ll dis[N]; bool vis[N]; void init() { ms(vis, false); ms(head, -1); cnt = 0; ms(tim, 0); } inline void add(int u, int v, ll w) { ed[cnt] = {u, v, w, head[u]}; head[u] = cnt++; } deque<int>q; inline bool spfa(int u){ dis[u] = 0; vis[u] = 1; q.push_back(u); while(!q.empty()){ u = q.front();q.pop_front(); vis[u] = 1; tim[u]++; if (tim[u] > sqrt(n + m)) return 0; for (int i = head[u]; ~i; i = ed[i].ne){ int &v = ed[i].v; ll &w = ed[i].w; if (dis[v] < dis[u] + w){ dis[v] = dis[u] + w; if (!q.empty() && dis[v] <= dis[q.front()]) q.push_back(v); else q.push_front(v); vis[v] = 1; } } } return 1; } int main() { int a, b, op; n = read(), m = read(); init(); for (int i = 0; i < m; ++i){ op = read(), a = read(), b = read(); if (op == 1) add(a, b, 0), add(b, a, 0); if (op == 2) add(a, b, 1); if (op == 3) add(b, a, 0); if (op == 4) add(b, a, 1); if (op == 5) add(a, b, 0); } for (int i = n; i >= 1; --i){ add(0, i, 1); } ll ans = 0; if (spfa(0)){ for (int i = 1; i <= n; ++i){ ans += dis[i]; } cout << ans << "\n"; } else cout << "-1\n"; return 0; }
|