Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <queue>
  5.  
  6. using namespace std;
  7.  
  8. const int INF = 1e9;
  9.  
  10. int n, m, dist[25000];
  11. vector< pair<int, int> > g[25000];
  12. bool mark[25000];
  13.  
  14. //queue
  15. const int N = 100001;
  16. int qdata[N], qnext[N], qhead[3], fr;
  17.  
  18. void push(int v, int x) {
  19. qdata[fr] = x;
  20. qnext[fr] = qhead[v];
  21. qhead[v] = fr;
  22. fr++;
  23. }
  24.  
  25. void pop(int v) {
  26. qhead[v] = qnext[qhead[v]];
  27. }
  28.  
  29. bool empty(int v) {
  30. return (qhead[v] == -1);
  31. }
  32.  
  33. int front(int v) {
  34. return qdata[qhead[v]];
  35. }
  36.  
  37.  
  38. int solve(int s, int f) {
  39. fr = 0;
  40. qhead[0] = -1;
  41. qhead[1] = -1;
  42. qhead[2] = -1;
  43.  
  44. for (int i = 0; i < n; i++) {
  45. dist[i] = INF;
  46. mark[i] = false;
  47. }
  48.  
  49. dist[s] = 0;
  50. push(0, s);
  51. while (!empty(0) || !empty(1) || !empty(2)) {
  52. int v = -1;
  53. if (!empty(0)) {
  54. v = front(0);
  55. pop(0);
  56. } else {
  57. swap(qhead[0], qhead[1]);
  58. swap(qhead[1], qhead[2]);
  59. continue;
  60. }
  61. if (mark[v] == true)
  62. continue;
  63. mark[v] = true;
  64.  
  65. int x, y;
  66. x = dist[v] / 1000;
  67. for (int i = 0; i < (int)g[v].size(); i++) {
  68. int u = g[v][i].first;
  69. int w = g[v][i].second;
  70. if (dist[v] + w < dist[u]) {
  71. dist[u] = dist[v] + w;
  72. y = dist[u] / 1000;
  73. if (y - x == 1)
  74. push(1, u);
  75. else
  76. push(2, u);
  77. }
  78. }
  79. }
  80. if (dist[f] == INF)
  81. return -1;
  82. return dist[f];
  83. }
  84.  
  85.  
  86. int main() {
  87. scanf("%d%d", &n, &m);
  88. int x, y, w;
  89. for (int i = 0; i < m; i++) {
  90. scanf("%d%d%d", &x, &y, &w);
  91. x--; y--;
  92. g[x].push_back({y, w});
  93. }
  94.  
  95. int k, s, f, ans;
  96. cin >> k;
  97. for (int i = 0; i < k; i++) {
  98. scanf("%d%d", &s, &f);
  99. s--; f--;
  100. ans = solve(s, f);
  101. printf("%d\n", ans);
  102. }
  103. return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement