Advertisement
Guest User

No_Idea

a guest
Oct 23rd, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <bitset>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. #define INF 0x7fffffff
  8. #define x first
  9. #define y second
  10.  
  11. vector<int> dijkstra(const vector<vector<pair<int, int>>> &Edges, const unsigned int N){
  12. /*
  13. Using an modification of dijkstra's algorithm.
  14.  
  15. This algorithm can have Edges with negative values.
  16. This algorithm is posible to check whether there is any negative cicle or not.
  17. */
  18. pair< int, pair < int, bitset< N > > > aux;
  19. priority_queue< pair< int, pair< int, bitset< N > > > > Heap;
  20. int Weight[N], Last_Inside[N], Inside_Now = 0;
  21. bitset< N > &bitaux;
  22.  
  23. for (int i = 0; i < N; i++){
  24. Last_Inside[i] = 0;
  25. Weight[i] = INF;
  26. }
  27.  
  28. Heap.push(make_pair(0, make_pair(0, bitset< N >())));
  29. while (!Heap.empty()){
  30. aux = Heap.top();
  31. aux.x *= -1; // Using NegaMax idea
  32. Heap.pop();
  33.  
  34. //check if it is smaller, instead of checked if it is visited
  35. if (Weight[aux.y.x] <= aux.x)
  36. continue;
  37.  
  38. //check if the border expands
  39. if (Weight[aux.y.x] == INF)
  40. Inside_Now++;
  41.  
  42. Weight[aux.y.x] = aux.x;
  43.  
  44. for (unsigned int i = 0; i < Edges[aux.y.x].size(); i++)
  45. if (Edges[aux.y.x][i].y + aux.x < Weight[Edges[aux.y.x][i].x]){
  46. bitaux = aux.y.y;
  47. if(bitaux[Edges[aux.y.x].x]){
  48. cout << "Negative Cicle";
  49. return vector<int>(Weight, Weight + N);
  50. }
  51. bitaux[Edges[aux.y.x].x] = true;
  52. Heap.push(make_pair(-(Edges[aux.y.x][i].y + aux.x), make_pair(Edges[aux.y.x][i].x, bitaux)));
  53. bitaux[Edges[aux.y.x].x] = false;
  54. }
  55.  
  56. }
  57. return vector<int>(Weight, Weight + N);
  58. }
  59.  
  60. int main(){
  61. ios::sync_with_stdio(false); cin.tie(0);
  62.  
  63. int N, M, from, to, w;
  64. cin >> N >> M;
  65.  
  66. vector<vector<pair<int, int>>> Edges(N);
  67. vector<int> temp;
  68.  
  69. for (int i = 0; i < M; i++){
  70. cin >> from >> to >> w;
  71. Edges[from].push_back(make_pair(to, w));
  72. }
  73.  
  74. temp = dijkstra(Edges, N);
  75.  
  76. cout << endl;
  77. for (int i = 0; i < N; i++)
  78. if (temp[i] != INF)
  79. cout << i << ": " << temp[i] << '\n';
  80. else
  81. cout << i << ": Don't pass here\n";
  82.  
  83. return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement