-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstras.cpp
More file actions
103 lines (83 loc) · 1.69 KB
/
dijkstras.cpp
File metadata and controls
103 lines (83 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//Dijkstras
#include <bits/stdc++.h>
using namespace std;
//edge of graph
struct edge
{
int u,v;
int weight;
edge(int _u,int _v, int _w)
{
u = _u;
v = _v;
weight = _w;
}
};
//store distance and edges
vector<int> dist(1000001,20000000);
vector<edge> adj[1000000];
//Dijkstras
void dijkstras(int start)
{
//Mark start node as zero
dist[start] = 0;
//priority queue in ascending order of weight
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
//push first element into pq
pq.push(make_pair(dist[start], start));
//loop till empty
while(!pq.empty())
{
//u is node and d is distance of that node from s
int u = pq.top().second;
int d = pq.top().first;
//remove edge
pq.pop();
//if distance is greater current distance then ignore
if(d > dist[u])
continue;
//loop through connected edges of u
for(int i = 0; i < adj[u].size(); i++)
{
//v is the node u is connceted to w is its weight
int v = adj[u][i].v;
int w = adj[u][i].weight;
//if w + curr w is less that in node v then store it
if(w + dist[u] < dist[v])
{
dist[v] = w + dist[u];
pq.push(make_pair(dist[v],v));
}
}
}
}
int main()
{
int n, m,q,s;
while(cin>>n>>m>>q>>s && (n!=0 || m != 0 || q!= 0 || s!= 0))
{
for(int i = 0; i < 1000001; i++)
{
dist[i] = 20000000;
}
for(int i = 0; i < m; i++)
{
int u,v,w;
cin>>u>>v>>w;
adj[u].push_back(edge(u,v,w));
}
dijkstras(s);
int query;
for(int i = 0; i < q; i++)
{
cin>>query;
if(dist[query] >= 20000000)
cout<<"Impossible"<<endl;
else
cout<<dist[query]<<endl;
}
for(int i = 0; i < 1000000; i++)
adj[i].clear();
}
return 0;
}