Advertisement
remember_Me

Untitled

Aug 10th, 2020
483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. //DIJKSTRA K SHORTEST PATH FROM SOURCE TO DESTINATION
  2.  
  3. #include <bits/stdc++.h>
  4. #define MOD                   (int)(1e9+7)
  5. #define SIZE                  (int)(1e5+5)
  6. #define all(x)                x.begin(),x.end()
  7. #define r_all(x)              x.rbegin(),x.rend()
  8. #define lb                    lower_bound
  9. #define ub                    upper_bound
  10. #define pb                    push_back
  11. #define F                     first
  12. #define S                     second
  13. #define IOfast                ios_base::sync_with_stdio(false); cin.tie(NULL);
  14. using namespace std;
  15. vector <pair<int,int64_t>> graph[(int)1e5 + 1]; // graph node,edge cost
  16.  
  17. multiset<int64_t> dist[(int)1e5 + 1]; //to store dist upto k size() for each node
  18.  
  19. void dikstra(int n,int k)
  20. {
  21.   set<pair<int64_t,int>> s;// cost,value;
  22.   s.insert({0,1});
  23.   dist[1].insert(0);
  24.  
  25.   while(s.size())
  26.   {
  27.      int64_t value  = (*s.begin()).F;
  28.      int vertex     = (*s.begin()).S;
  29.      int cnt = dist[vertex].count(value);// how many same value dist
  30.  
  31.      s.erase(s.begin());
  32.      for(auto child:graph[vertex])
  33.      {
  34.         for(int i=1;i<=cnt;i++)
  35.         {
  36.           if(dist[child.F].size() < k)
  37.           {
  38.             dist[child.F].insert(value + child.S);
  39.             s.insert({value + child.S,child.F});
  40.           }
  41.           else
  42.           {
  43.              auto it = dist[child.F].lb(value + child.S);
  44.              if(it == dist[child.F].end()) continue;
  45.  
  46.              if(dist[child.F].count( *(dist[child.F].rbegin()) ) == 1)
  47.                 s.erase({*(dist[child.F].rbegin()),child.F});
  48.  
  49.             dist[child.F].erase(--dist[child.F].end());
  50.  
  51.             s.insert({value + child.S, child.F});
  52.             dist[child.F].insert(value + child.S);;
  53.           }
  54.         }
  55.      }
  56.   }
  57.  
  58.   int done = 0;
  59.   for(auto item:dist[n])
  60.      if(++done > k)
  61.        break;
  62.      else
  63.        cout<<item<<" ";
  64. }
  65.  
  66. void solve()
  67. {
  68.   int n,m,k;
  69.   cin>>n>>m>>k;
  70.   while(m--)
  71.   {
  72.     int u,v,cost;
  73.     cin>>u>>v>>cost;
  74.     graph[u].pb({v,cost});
  75.   }
  76.   dikstra(n,k);
  77. }
  78.  
  79. int main()
  80. {
  81.   IOfast;
  82.   solve();
  83.  
  84.   return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement