Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define int long long
- #define For(i,z) for(int i=0;i<z;i++)
- using namespace std;
- const int N = 5e5+5;
- const int INF = 1e12;
- vector<int> gr[N];
- vector<int> rev[N];
- int ans[N][3];
- struct node
- {
- int flag;
- int dst;
- int v;
- node(){flag = 0; dst = 0; v = 0;}
- bool operator > (const node &ot) const {
- return (dst > ot.dst);
- }
- };
- int32_t main()
- {
- //freopen("input.txt","r", stdin);
- ios_base::sync_with_stdio(false);
- int n, m;
- cin >> n >> m;
- For (i, m)
- {
- int a, b;
- cin >> a >> b;
- a--; b--;
- gr[a].push_back(b);
- rev[b].push_back(a);
- rev[a].push_back(b);
- }
- For (i, N) For (j, 3) ans[i][j] = INF;
- ans[0][0] = 0;
- priority_queue<node, vector<node>, greater<node> > q;
- q.push(node());
- while (!q.empty())
- {
- node cur = q.top();
- q.pop();
- if (ans[cur.v][cur.flag] < cur.dst) continue;
- if (cur.flag == 0)
- for (int &i : rev[cur.v])
- if (ans[i][0] > cur.dst+1)
- {
- ans[i][0] = cur.dst+1;
- node nxt; nxt.v = i; nxt.dst = cur.dst+1;
- q.push(nxt);
- }
- if (cur.flag <= 1)
- for (int &i : gr[cur.v])
- if (ans[i][1] > cur.dst && ans[i][0] > cur.dst)
- {
- ans[i][1] = cur.dst;
- node nxt; nxt.v = i; nxt.flag = 1; nxt.dst = cur.dst;
- q.push(nxt);
- }
- if (cur.flag)
- for (int &i : rev[cur.v])
- if (ans[i][2]>cur.dst+1 && ans[i][1]>cur.dst+1 && ans[i][0] > cur.dst+1)
- {
- ans[i][2] = cur.dst + 1;
- node nxt; nxt.v = i; nxt.flag = 2; nxt.dst = cur.dst + 1;
- q.push(nxt);
- }
- }
- int mn = INF;
- For (i, 3) mn = min(mn, ans[n-1][i]);
- if (mn == INF)
- cout << "-1\n";
- else
- cout << mn;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement