-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathProblem E.cpp
More file actions
71 lines (60 loc) · 1.86 KB
/
Problem E.cpp
File metadata and controls
71 lines (60 loc) · 1.86 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
#include <bits/stdc++.h>
using namespace std;
#define intPair pair<int, int>
const int maxCities = 500;
vector<intPair> G[maxCities]; // graph
int cost[maxCities]; // minimum cost of travelling from source to each city
void dijkstra(int source)
{
priority_queue<intPair, vector<intPair>, greater<intPair> > pq;
pq.push({source, 0});
cost[source] = 0;
while (!pq.empty())
{
int thisNode = pq.top().first;
int thisCost = pq.top().second;
pq.pop();
if (thisCost != cost[thisNode]) continue; // older node -> ignore
for (auto neighbour:G[thisNode]) // for each neighbour
{
int neighbourNode = neighbour.first;
int neighbourCost = max(cost[thisNode], neighbour.second); // maximum value on path to this this node from source
if ((cost[neighbourNode] == -1) || (cost[neighbourNode] > neighbourCost)) // if this value is less than current cost, take it
{
cost[neighbourNode] = neighbourCost;
pq.push({neighbourNode, neighbourCost});
}
}
}
}
int main()
{
int T;
cin>>T;
for (int i=1; i<=T; i++)
{
int cities, roads;
cin>>cities>>roads;
for (int j=0; j<cities; j++) // clear graph and cost values for new source
{
G[j].clear();
cost[j] = -1;
}
for (int j=1; j<=roads; j++)
{
int u, v, w;
cin>>u>>v>>w;
G[u].push_back({v, w}); // bi-directional
G[v].push_back({u, w});
}
int t;
cin>>t;
dijkstra(t);
cout<<"Case "<<i<<":"<<endl; // output
for (int j=0; j<cities; j++)
{
if (cost[j] == -1) cout << "Impossible" << endl;
else cout << cost[j] << endl;
}
}
}