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
| #include <bits/stdc++.h> using namespace std;
template <typename T> void r1(T &x) { x = 0; char c(getchar()); int f(1); for(; c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1; for(; '0' <= c && c <= '9';c = getchar()) x = (x * 10) + (c ^ 48); x *= f; }
template <typename T,typename... Args> inline void r1(T& t, Args&... args) { r1(t); r1(args...); }
const int maxn = 5e5 + 5; const int maxm = maxn << 1;
struct Node { int u, v, l, r, opt; Node(int a = 0,int b = 0,int c = 0,int d = 0,int e = 0) : u(a), v(b), l(c), r(d), opt(e) {} int operator < (const Node &z) const { return l > z.l; } };
priority_queue<Node> q;
vector<Node> vc[maxn][2]; int f[maxn][2];
int n, m;
signed main() {
int i, j; r1(n, m), memset(f, -0x3f, sizeof(f)); if(n == 1) return puts("0"), 0; for(i = 1; i <= m; ++ i) { int u, v, l, r; r1(u, v, l, r); -- r; int opt = (r - l) & 1; auto Add = [&] (int u,int v,int l,int r) { q.push(Node (u, v, l, r, 1)); }; Add(u, v, l, r - opt); Add(u, v, l + 1, r - (!opt)); } f[1][0] = 0; auto Solve = [&] (int u,int v,int l,int r) { int opt(l & 1); if(f[u][opt] >= l) { if(v == n) { printf("%d\n", l + 1); exit(0); } if(f[v][!opt] <= r) { f[v][!opt] = r + 1; for(auto V : vc[v][!opt]) { q.push(Node(V.u, V.v, l + 1, V.r)); } } } else vc[u][opt].push_back(Node(u, v, l, r)); }; while(!q.empty()) { Node u = q.top(); q.pop(); if(u.l > u.r) continue; Solve(u.u, u.v, u.l, u.r); if(u.opt) Solve(u.v, u.u, u.l, u.r); } puts("-1"); return 0; }
|