-
Notifications
You must be signed in to change notification settings - Fork 65
/
10278 Fire Station.cpp
118 lines (98 loc) · 3 KB
/
10278 Fire Station.cpp
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <sstream>
using namespace std;
const int NumIntersections = 501;
const int NumFireStations = 101;
const int NoPath = 1e9;
int F, N;
// Will start off with NoPath
int distances[NumIntersections][NumIntersections];
int distanceToFire[NumIntersections];
int fireStationIntersections[NumFireStations];
int main()
{
int T;
cin >> T;
string sep = "";
while (T--)
{
cout << sep;
sep = "\n";
cin >> F >> N;
for (int i = 0; i < N; ++i)
{
distanceToFire[i] = NoPath;
for (int j = 0; j < N; ++j)
{
distances[i][j] = NoPath;
}
distances[i][i] = 0;
}
for (int i = 0; i < F; ++i)
{
int station;
cin >> station;
--station;
// intersection already identified as station
if (distanceToFire[station] == 0)
{
--i;
--F;
}
else
{
distanceToFire[station] = 0;
fireStationIntersections[i] = station;
}
}
cin.ignore();
string line;
while (getline(cin, line) && line != "")
{
stringstream ss(line);
int s, e, dist;
ss >> s >> e >> dist;
--s; --e;
distances[s][e] = distances[e][s] = min(distances[s][e], dist);
}
// Calculate all distances first
for (int k = 0; k < N; ++k)
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
distances[i][j] = min(distances[i][j], distances[i][k] + distances[k][j]);
// Calcuate distance to closest fire station
for (int i = 0; i < N; ++i)
{
// Not at a fire station already
if (distanceToFire[i])
{
for (int j = 0; j < F; ++j)
{
distanceToFire[i] = min(distanceToFire[i], distances[i][fireStationIntersections[j]]);
}
}
}
// Calculate which is the best to place a new one
int bestMaxDist = NoPath;
int bestIntersection = 0; // In case all have fire station, doesn't matter
for (int i = 0; i < N; ++i)
{
// Not at a fire station already
if (distanceToFire[i])
{
// Will try picking i as the new fire station
int maxDist = 0;
for (int j = 0; j < N; ++j)
{
maxDist = max(maxDist, min(distanceToFire[j], distances[j][i]));
}
if (maxDist < bestMaxDist)
{
bestMaxDist = maxDist;
bestIntersection = i;
}
}
}
cout << (bestIntersection + 1) << '\n';
}
}