Skip to content

Commit eadf914

Browse files
Distance from Source Graph
1 parent 9dcf24a commit eadf914

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

dist_from_source.cpp

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//https://www.codechef.com/problems/BUG2K17B
2+
#include<bits/stdc++.h>
3+
#define mp pair<int,int>
4+
using namespace std;
5+
6+
int debugg=0;
7+
class Node{
8+
public:
9+
int dist;
10+
vector<pair<int,int> > next;//first contains city index .. second contains distance
11+
12+
void clear(){
13+
dist=INT_MAX;
14+
next.clear();
15+
}
16+
} node[100002];
17+
18+
struct priority_fxn{
19+
bool operator() (int a,int b){
20+
return node[a].dist > node[b].dist;
21+
}
22+
};
23+
void dijakstra(int source){
24+
int n,d,temp;
25+
priority_queue<int,vector<int>,priority_fxn> q;
26+
27+
//init queue
28+
node[source].dist=0;
29+
q.push(source);
30+
31+
while(!q.empty()){
32+
temp=q.top();
33+
for(auto elem : node[temp].next){
34+
n=elem.first;
35+
d=elem.second;
36+
if(node[n].dist > node[temp].dist + d){
37+
node[n].dist = node[temp].dist + d;
38+
q.push(n);
39+
}
40+
}
41+
q.pop();
42+
}
43+
}
44+
45+
int main(){
46+
int t,a,b,c,n,p;
47+
cin>>t;
48+
while(t--){
49+
cin>>n>>p;
50+
for(int i=1;i<=n;i++)
51+
node[i].clear();
52+
while(p--){
53+
cin>>a>>b>>c;
54+
node[a].next.push_back(mp(b,c));
55+
node[b].next.push_back(mp(a,c));
56+
}
57+
dijakstra(1);
58+
if(node[n].dist==INT_MAX)cout<<"NONE"<<endl;
59+
else
60+
cout<<node[n].dist<<endl;
61+
}
62+
}

0 commit comments

Comments
 (0)