Advertisement
aniket123422

tsp approximation

Dec 5th, 2022
697
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | Source Code | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void primMST(vector<vector<pair<int,int>>> &adj, vector<vector<int>> &mst)
  5. {
  6.     int V = adj.size();
  7.    
  8.     vector<int> parent(V,-1);
  9.     vector<int> key(V,INT_MAX);
  10.     vector<int> visited(V,0);
  11.  
  12.     priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
  13.  
  14.     //  for making it min heap we have to use this syntax
  15.     //  priority_queue<int, vector<int>, greater<int>> pq --> for making it min heap
  16.     //  priority_queue<int>pq--> by default it makes max heap
  17.     //  or we can also use to max priority queue and insert elements with multiplying -1
  18.     //  which will make minimum element largest and maximum element smallest and we will
  19.     //  access them with the help of -1 multiplication
  20.  
  21.  
  22.     key[0] = 0;
  23.     pq.push({0,0});
  24.  
  25.     while(!pq.empty()){
  26.  
  27.         pair<int,int> p = pq.top();
  28.         pq.pop();
  29.  
  30.         int wt = p.first;
  31.         int u = p.second;
  32.  
  33.         if(visited[u])
  34.             continue;
  35.        
  36.         visited[u] = 1;
  37.  
  38.         for(auto v : adj[u]){
  39.             if(!visited[v.first] && v.second < key[v.first]){
  40.                 key[v.first] = v.second;
  41.                 pq.push({key[v.first],v.first});
  42.                 parent[v.first] = u;
  43.             }
  44.         }
  45.     }
  46.  
  47.     for(int i = 1; i < V; i++){
  48.         mst[parent[i]].push_back(i);
  49.     }
  50.  
  51.  
  52.     return;
  53.  
  54. }
  55.  
  56. void dfs(vector<vector<int>> &mst, vector<int> &visited, vector<int> &tsp, int u){
  57.    
  58.     visited[u] = true;
  59.     tsp.push_back(u);
  60.  
  61.     for(auto v : mst[u]){
  62.         if(!visited[v]){
  63.             dfs(mst,visited,tsp,v);
  64.         }
  65.     }
  66. }
  67.  
  68. int main(){
  69.     int n,e;
  70.     cin >> n >> e;
  71.  
  72.     vector<vector<pair<int,int>>> adj(n);
  73.  
  74.     for(int i = 0; i < e; i++){
  75.         int u,v,w;
  76.         cin >> u >> v >> w;
  77.  
  78.         adj[u].push_back({v,w});
  79.         adj[v].push_back({u,w});
  80.     }
  81.  
  82.     vector<vector<int>> mst(n);
  83.     primMST(adj,mst);
  84.     vector<int> visited(n,0);
  85.  
  86.     vector<int> tsp;
  87.     dfs(mst,visited,tsp,0);
  88.  
  89.     tsp.push_back(0);
  90.  
  91.     for(auto i : tsp){
  92.         cout << i << " ";
  93.     }
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement