0% found this document useful (0 votes)
37 views2 pages

Dijkstra Shortest Reach 2

This document defines various typedefs for common data structures like vectors, pairs, queues, sets, and maps. It also includes functions for initializing a map, running Dijkstra's algorithm to find shortest paths in a graph, and taking input and output for testing shortest path problems.

Uploaded by

gggy9727799900
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views2 pages

Dijkstra Shortest Reach 2

This document defines various typedefs for common data structures like vectors, pairs, queues, sets, and maps. It also includes functions for initializing a map, running Dijkstra's algorithm to find shortest paths in a graph, and taking input and output for testing shortest path problems.

Uploaded by

gggy9727799900
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include<bits/stdc++.

h>
using namespace std;

typedef long long int ll;


typedef pair<int, int> pi2;
typedef pair<int, ll> pill;
typedef pair<int, pi2> pi3;
typedef vector<int> vi;
typedef vector<vi> v2i;
typedef vector<v2i> v3i;
typedef queue<int> qi;
typedef vector<pi2> vpi2;
typedef vector<pi3> vpi3;
typedef priority_queue<int> pqi;
typedef priority_queue<pi2> pqpi2;
typedef set<int> si;
typedef vector<si> vsi;
typedef set<pi2> spi2;
typedef set<pi3> spi3;
typedef set<int>::iterator sit;
typedef map<int, int> mi2;

void ie(mi2 &map, int v, int w){


if(map.count(v)==1){
if(w<map[v]){
map[v]=w;
}
}
else{
map.insert(make_pair(v,w));
}
}

void dijkstra(int n, vector<mi2> &adj, vi &dis){


mi2::iterator itr;
vi vis(n+1,0);
for (int c=0;c<n;c++){
int min=INT_MAX,minv,s;
for(int j=0;j<n+1;j++){
if(!vis[j]&&dis[j]<min){
min=dis[j];
minv=j;
}
}
if(min==INT_MAX) {
break;
}
s=minv;
vis[s]=1;
for(itr=adj[s].begin();itr!=adj[s].end();++itr){
int v,w,m;
v=itr->first;
w=itr->second;
m=dis[s]+w;
if(!vis[v]&&dis[v]>m){
dis[v]=m;
}
}
}
}

int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int t;
cin>>t;
for(int i=0;i<t;i++){
int n,m;
cin>>n>>m;
vector<mi2> adj(n+1);
for(int j=0;j<m;j++){
int u,v,w;
cin>>u>>v>>w;
ie(adj[u],v,w);
ie(adj[v],u,w);
}
int s;
cin>>s;
vi dis(n+1,INT_MAX);
dis[s]=0;
dijkstra(n, adj, dis);
for(int j=1;j<n+1;j++){
if(dis[j]!=0){
if(dis[j]==INT_MAX){
cout<<"-1 ";

}
else{
cout<<dis[j]<<" ";
}
}
}
cout<<endl;
}
}

You might also like