[text] priyanshu

Viewer

copydownloadembedprintName: priyanshu
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int inf=1e7;
  4. int main(){
  5.     int n,m;
  6.     cin>>n>>m;
  7.     vector<int>dist(n+1,inf);
  8.     vector<pair<int,int>>g[n+1];
  9.     for(int i=0;i<m;i++){
  10.         int a,b,w;
  11.         cin>>a>>b>>w;
  12.         g[a].push_back({b,w});
  13.         g[b].push_back({a,w});
  14.     }
  15.     set<pair<int,int>>s;
  16.     s.insert({0,0});
  17.     dist[0]=0;
  18.     while(!s.empty()){
  19.         auto x= *(s.begin());
  20.         s.erase(x);
  21.         int node=x.second;
  22.         int d=x.first;
  23.         for(int i=0;i<g[node].size();i++){
  24.             auto v=g[node][i];
  25.             int node1=v.first;
  26.             int d1=  v.second;
  27.             if(dist[node1]>(d1+d)){
  28.                 dist[node1]=d1+d;
  29.                 s.insert(dist[node1],node1);
  30.             }
  31.         }
  32. }
  33. for(int i=0;i<dist.size();i++){
  34.     cout<<dist[i]<<endl;
  35. }
  36.  
  37. }
  38.  

Editor

You can edit this paste and save as new:


File Description
  • priyanshu
  • Paste Code
  • 06 May-2024
  • 862 Bytes
You can Share it: