Repository navigation
Expand file tree
/
Copy pathwow.cpp
More file actions
398 lines (341 loc) · 12.5 KB
/
Copy pathwow.cpp
File metadata and controls
398 lines (341 loc) · 12.5 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// BaseballElimination.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <queue>
#include <stdexcept>
#include <algorithm>
#include <climits>
#include <numeric>
#include <set>
using namespace std;
// -----------------------------
// Division Class
// -----------------------------
class Division {
private:
int numTeams;
vector<string> teamNames;
vector<int> wins;
vector<int> losses;
vector<int> remainingGames;
vector<vector<int>> gamesAgainstMatrix;
int stringToNumber(const string& s) const {
return stoi(s);
}
public:
Division(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
throw runtime_error("Error: File '" + filename + "' does not exist.");
}
string line;
// Read number of teams
if (!getline(file, line)) {
throw runtime_error("Error: The input file is empty.");
}
numTeams = stringToNumber(line);
if (numTeams < 2) {
throw runtime_error("Error: At least two teams are required.");
}
// Read team data
while (getline(file, line)) {
if (line.empty()) continue; // Skip empty lines
istringstream ss(line);
string team;
int win, loss, remaining;
if (!(ss >> team >> win >> loss >> remaining)) {
throw runtime_error("Error: Invalid data format for team statistics.");
}
vector<int> gamesAgainst;
for (int i = 0; i < numTeams; ++i) {
int games;
if (!(ss >> games)) {
throw runtime_error("Error: Insufficient games against data for team " + team);
}
gamesAgainst.push_back(games);
}
// Data consistency check
int totalGamesAgainst = accumulate(gamesAgainst.begin(), gamesAgainst.end(), 0);
if (totalGamesAgainst != remaining) {
throw runtime_error("Error: Total games against other teams does not match remaining games for team " + team);
}
teamNames.push_back(team);
wins.push_back(win);
losses.push_back(loss);
remainingGames.push_back(remaining);
gamesAgainstMatrix.push_back(gamesAgainst);
}
// Validate input
if (teamNames.size() != numTeams) {
throw runtime_error("Error: Mismatch between number of teams and team data provided.");
}
file.close();
}
// Getter methods
int getNumTeams() const { return numTeams; }
const vector<string>& getTeamNames() const { return teamNames; }
const vector<int>& getWins() const { return wins; }
const vector<int>& getLosses() const { return losses; }
const vector<int>& getRemainingGames() const { return remainingGames; }
const vector<vector<int>>& getGamesAgainstMatrix() const { return gamesAgainstMatrix; }
};
// -----------------------------
// Graph Class
// -----------------------------
class Graph {
private:
int numVertices;
vector<vector<int>> capacityMatrix;
public:
Graph(int vertices) : numVertices(vertices), capacityMatrix(vertices, vector<int>(vertices, 0)) {}
void addEdge(int from, int to, int capacity) {
capacityMatrix[from][to] = capacity;
}
const vector<vector<int>>& getCapacityMatrix() const { return capacityMatrix; }
int getNumVertices() const { return numVertices; }
};
// -----------------------------
// Ford-Fulkerson Class (Edmonds-Karp Algorithm)
// -----------------------------
class FordFulkerson {
private:
const Graph& graph;
int source;
int sink;
vector<int> parent;
vector<vector<int>> residual;
bool bfs() {
parent.assign(graph.getNumVertices(), -1);
parent[source] = -2;
queue<int> q;
q.push(source);
while (!q.empty()) {
int current = q.front();
q.pop();
for (int next = 0; next < graph.getNumVertices(); ++next) {
if (parent[next] == -1 && residual[current][next] > 0) {
parent[next] = current;
if (next == sink) {
return true;
}
q.push(next);
}
}
}
return false;
}
public:
FordFulkerson(const Graph& g, int s, int t)
: graph(g), source(s), sink(t), parent(g.getNumVertices(), -1), residual(g.getCapacityMatrix()) {}
int getMaxFlow() {
int maxFlow = 0;
while (bfs()) {
// Find bottleneck capacity
int pathFlow = INT_MAX;
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
pathFlow = min(pathFlow, residual[u][v]);
}
// Update residual capacities
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
residual[u][v] -= pathFlow;
residual[v][u] += pathFlow;
}
maxFlow += pathFlow;
}
return maxFlow;
}
const vector<vector<int>>& getResidualGraph() const {
return residual;
}
const vector<int>& getParent() const {
return parent;
}
};
// -----------------------------
// FlowNetwork Class
// -----------------------------
class FlowNetwork {
private:
Graph graph;
int source;
int sink;
int teamIndex; // Index of the team being analyzed
int numTeams;
int numGames;
int gameNodeStart;
int teamNodeStart;
vector<string> teamNames;
vector<int> wins;
vector<int> remainingGames;
int adjustedTeamNode(int originalIndex) const {
return teamNodeStart + originalIndex - (originalIndex > teamIndex ? 1 : 0);
}
public:
FlowNetwork(const Division& division, int teamIdx)
: teamIndex(teamIdx),
teamNames(division.getTeamNames()),
wins(division.getWins()),
remainingGames(division.getRemainingGames()),
numTeams(division.getNumTeams()),
numGames(0), // Initialize to 0, will calculate in the constructor body
graph(1), // Temporary initialization, will be properly set later
source(0),
sink(1) // Temporary value, will be updated
{
// Calculate number of game nodes
const auto& gamesAgainst = division.getGamesAgainstMatrix();
for (int i = 0; i < numTeams; ++i) {
for (int j = i + 1; j < numTeams; ++j) {
if (i != teamIndex && j != teamIndex) {
int gamesLeft = gamesAgainst[i][j];
if (gamesLeft > 0) {
numGames++;
}
}
}
}
// Total nodes = source + game nodes + team nodes + sink
int totalNodes = 2 + numGames + (numTeams - 1);
// Properly initialize the graph with the correct number of nodes
graph = Graph(totalNodes);
sink = totalNodes - 1;
gameNodeStart = 1;
teamNodeStart = gameNodeStart + numGames;
// Add edges from source to game nodes and from game nodes to team nodes
int gameNode = gameNodeStart;
for (int i = 0; i < numTeams; ++i) {
if (i == teamIndex) continue;
for (int j = i + 1; j < numTeams; ++j) {
if (j == teamIndex) continue;
int gamesLeft = gamesAgainst[i][j];
if (gamesLeft > 0) {
// Edge from source to game node
graph.addEdge(source, gameNode, gamesLeft);
// Edges from game node to team nodes
int teamNodeI = adjustedTeamNode(i);
int teamNodeJ = adjustedTeamNode(j);
graph.addEdge(gameNode, teamNodeI, INT_MAX);
graph.addEdge(gameNode, teamNodeJ, INT_MAX);
gameNode++;
}
}
}
// Calculate the maximum number of games Team X can win
int maxPossibleWins = wins[teamIndex] + remainingGames[teamIndex];
// Add edges from team nodes to sink
for (int i = 0; i < numTeams; ++i) {
if (i == teamIndex) continue;
int capacity = maxPossibleWins - wins[i];
if (capacity < 0) {
capacity = 0; // Team already has more wins than Team X can achieve
}
int teamNode = adjustedTeamNode(i);
graph.addEdge(teamNode, sink, capacity);
}
}
bool isEliminated(bool verbose = false) const {
// Run Ford-Fulkerson algorithm
FordFulkerson ff(graph, source, sink);
int maxFlow = ff.getMaxFlow();
// Calculate total remaining games (from source)
int totalGames = 0;
const auto& capacityMatrix = graph.getCapacityMatrix();
for (int capacity : capacityMatrix[source]) {
totalGames += capacity;
}
if (verbose) {
cout << "Team: " << teamNames[teamIndex] << endl;
cout << "Max Flow: " << maxFlow << endl;
cout << "Total Remaining Games: " << totalGames << endl;
}
return maxFlow < totalGames;
}
vector<string> getEliminationCertificate() const {
// Run Ford-Fulkerson algorithm
FordFulkerson ff(graph, source, sink);
ff.getMaxFlow();
// Perform a BFS on the residual graph to find the reachable nodes from source
vector<bool> visited(graph.getNumVertices(), false);
queue<int> q;
q.push(source);
visited[source] = true;
const auto& residual = ff.getResidualGraph();
while (!q.empty()) {
int current = q.front();
q.pop();
for (int next = 0; next < graph.getNumVertices(); ++next) {
if (!visited[next] && residual[current][next] > 0) {
visited[next] = true;
q.push(next);
}
}
}
// Collect team nodes that are reachable from the source
vector<string> certificate;
for (int i = 0; i < numTeams; ++i) {
if (i == teamIndex) continue;
int teamNode = adjustedTeamNode(i);
if (visited[teamNode]) {
certificate.push_back(teamNames[i]);
}
}
return certificate;
}
};
// -----------------------------
// Main Function
// -----------------------------
int main() {
string filename;
cout << "Enter the input file name: ";
cin >> filename;
cout << endl;
try {
Division division(filename);
int numTeams = division.getNumTeams();
for (int teamIndex = 0; teamIndex < numTeams; ++teamIndex) {
// Trivial elimination check
int maxPossibleWins = division.getWins()[teamIndex] + division.getRemainingGames()[teamIndex];
bool triviallyEliminated = false;
string eliminationReason = "";
for (int i = 0; i < numTeams; ++i) {
if (i == teamIndex) continue;
if (division.getWins()[i] > maxPossibleWins) {
triviallyEliminated = true;
eliminationReason = division.getTeamNames()[i] + " already has more wins than " + division.getTeamNames()[teamIndex] + " can achieve.";
break;
}
}
if (triviallyEliminated) {
cout << division.getTeamNames()[teamIndex] << " is trivially eliminated." << endl;
cout << "Reason: " << eliminationReason << endl;
cout << endl;
} else {
// Non-trivial elimination check using Flow Network
FlowNetwork fn(division, teamIndex);
if (fn.isEliminated()) {
vector<string> certificate = fn.getEliminationCertificate();
cout << division.getTeamNames()[teamIndex] << " is eliminated." << endl;
cout << "They are eliminated by the subset { ";
for (const auto& team : certificate) {
cout << team << " ";
}
cout << "}." << endl;
cout << endl;
} else {
cout << division.getTeamNames()[teamIndex] << " is not eliminated." << endl;
cout << endl;
}
}
}
} catch (const exception& e) {
cerr << e.what() << endl;
return 1;
}
return 0;
}