Advertisement
Guest User

Untitled

a guest
Jan 21st, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define int long long
  4. #define For(i,z) for(int i=0;i<z;i++)
  5.  
  6. using namespace std;
  7.  
  8. const int N = 5e5+5;
  9. const int INF = 1e12;
  10.  
  11. vector<int> gr[N];
  12. vector<int> rev[N];
  13.  
  14. int ans[N][3];
  15.  
  16. struct node
  17. {
  18. int flag;
  19. int dst;
  20. int v;
  21. node(){flag = 0; dst = 0; v = 0;}
  22. bool operator > (const node &ot) const {
  23. return (dst > ot.dst);
  24. }
  25. };
  26.  
  27. int32_t main()
  28. {
  29. //freopen("input.txt","r", stdin);
  30.  
  31. ios_base::sync_with_stdio(false);
  32.  
  33. int n, m;
  34. cin >> n >> m;
  35.  
  36. For (i, m)
  37. {
  38. int a, b;
  39. cin >> a >> b;
  40. a--; b--;
  41. gr[a].push_back(b);
  42. rev[b].push_back(a);
  43. rev[a].push_back(b);
  44. }
  45.  
  46. For (i, N) For (j, 3) ans[i][j] = INF;
  47.  
  48. ans[0][0] = 0;
  49.  
  50. priority_queue<node, vector<node>, greater<node> > q;
  51.  
  52. q.push(node());
  53. while (!q.empty())
  54. {
  55. node cur = q.top();
  56. q.pop();
  57. if (ans[cur.v][cur.flag] < cur.dst) continue;
  58.  
  59. if (cur.flag == 0)
  60. for (int &i : rev[cur.v])
  61. if (ans[i][0] > cur.dst+1)
  62. {
  63. ans[i][0] = cur.dst+1;
  64. node nxt; nxt.v = i; nxt.dst = cur.dst+1;
  65. q.push(nxt);
  66. }
  67. if (cur.flag <= 1)
  68. for (int &i : gr[cur.v])
  69. if (ans[i][1] > cur.dst && ans[i][0] > cur.dst)
  70. {
  71. ans[i][1] = cur.dst;
  72. node nxt; nxt.v = i; nxt.flag = 1; nxt.dst = cur.dst;
  73. q.push(nxt);
  74. }
  75.  
  76. if (cur.flag)
  77. for (int &i : rev[cur.v])
  78. if (ans[i][2]>cur.dst+1 && ans[i][1]>cur.dst+1 && ans[i][0] > cur.dst+1)
  79. {
  80. ans[i][2] = cur.dst + 1;
  81. node nxt; nxt.v = i; nxt.flag = 2; nxt.dst = cur.dst + 1;
  82. q.push(nxt);
  83. }
  84. }
  85.  
  86. int mn = INF;
  87. For (i, 3) mn = min(mn, ans[n-1][i]);
  88. if (mn == INF)
  89. cout << "-1\n";
  90. else
  91. cout << mn;
  92.  
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement