-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirectedgraph.cpp
More file actions
695 lines (510 loc) · 19.4 KB
/
directedgraph.cpp
File metadata and controls
695 lines (510 loc) · 19.4 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
#include "graph.h"
#include "directedgraph.h"
#include <algorithm>
#include <stack>
#include <queue>
#include <climits>
#include <set>
void DirectedGraph::generateGraph(bool allowNegativeWeights) {
generateGraph(allowNegativeWeights, -1);
}
void DirectedGraph::generateGraph(bool allowNegativeWeights, int edgeCount = -1) {
std::random_device rd;
std::mt19937 gen(rd());
int minW = allowNegativeWeights ? DEFAULT_NMIN_WEIGHT : DEFAULT_MIN_WEIGHT;
int maxW = DEFAULT_MAX_WEIGHT;
std::uniform_int_distribution<int> weightDist(minW, maxW);
clearMatrix();
generateConnectedDAG(gen, weightDist);
generateCapacityAndCostMatrices(gen);
}
void DirectedGraph::addEdge(int from, int to, int weight){
validateVertex(from);
validateVertex(to);
set(from, to, weight);
}
void DirectedGraph::printInfo() const {
std::cout << "Directed Graph (may be disconnected)\n";
std::cout << "Vertices: " << getRows() << "\n";
int edgeCount = 0;
for (int i = 0; i < getRows(); ++i) {
for (int j = 0; j < getCols(); ++j) {
if (get(i, j)) edgeCount++;
}
}
std::cout << "Edges: " << edgeCount << "\n";
auto [minW, maxW] = findMinMaxWeights();
std::cout << "Min weight: " << minW << ", Max weight: " << maxW << "\n";
}
void DirectedGraph::clearMatrix() {
for (int i = 0; i < getRows(); ++i) {
for (int j = 0; j < getCols(); ++j) {
set(i, j, 0);
}
}
}
void DirectedGraph::generateConnectedDAG(std::mt19937& gen,
std::uniform_int_distribution<int>& weightDist) {
int vertices = getRows();
for (int i = 0; i < vertices - 1; ++i) {
int weight;
do {
weight = weightDist(gen);
} while (weight == 0);
set(i, i + 1, weight);
}
std::uniform_real_distribution<double> probDist(0.0, 1.0);
for (int i = 0; i < vertices; ++i) {
for (int j = i + 1; j < vertices; ++j) {
if (i + 1 != j) {
double distance = j - i;
double prob = champernownePDF(distance);
if (probDist(gen) < prob) {
int weight;
do {
weight = weightDist(gen);
} while (weight == 0);
set(i, j, weight);
}
}
}
}
}
Graph::ShimbelResult DirectedGraph::calculateShimbelGeneral() const {
int n = getRows();
ShimbelResult result;
result.min_paths = std::vector<std::vector<int>>(n, std::vector<int>(n, INT_MAX));
result.max_paths = std::vector<std::vector<int>>(n, std::vector<int>(n, INT_MIN));
result.reachable = std::vector<std::vector<bool>>(n, std::vector<bool>(n, false));
for (int i = 0; i < n; ++i) {
result.min_paths[i][i] = 0;
result.max_paths[i][i] = 0;
result.reachable[i][i] = true;
for (int j = 0; j < n; ++j) {
if (get(i, j) != 0) {
result.min_paths[i][j] = get(i, j);
result.max_paths[i][j] = get(i, j);
result.reachable[i][j] = true;
}
}
}
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (result.min_paths[i][k] != INT_MAX && result.min_paths[k][j] != INT_MAX) {
if (result.min_paths[i][j] > result.min_paths[i][k] + result.min_paths[k][j]) {
result.min_paths[i][j] = result.min_paths[i][k] + result.min_paths[k][j];
result.reachable[i][j] = true;
}
}
if (result.max_paths[i][k] != INT_MIN && result.max_paths[k][j] != INT_MIN) {
if (result.max_paths[i][j] < result.max_paths[i][k] + result.max_paths[k][j]) {
result.max_paths[i][j] = result.max_paths[i][k] + result.max_paths[k][j];
result.reachable[i][j] = true;
}
}
}
}
}
return result;
}
Graph::ShimbelResult DirectedGraph::calculateShimbel(int steps) const {
int n = getRows();
ShimbelResult result;
result.min_paths = std::vector<std::vector<int>>(n, std::vector<int>(n, INT_MAX));
result.max_paths = std::vector<std::vector<int>>(n, std::vector<int>(n, INT_MIN));
result.reachable = std::vector<std::vector<bool>>(n, std::vector<bool>(n, false));
if (steps == 0) {
for (int i = 0; i < n; ++i) {
result.min_paths[i][i] = 0;
result.max_paths[i][i] = 0;
result.reachable[i][i] = true;
}
return result;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (get(i, j) != 0) {
result.min_paths[i][j] = get(i, j);
result.max_paths[i][j] = get(i, j);
result.reachable[i][j] = true;
}
}
}
for (int s = 2; s <= steps; ++s) {
auto temp_min = std::vector<std::vector<int>>(n, std::vector<int>(n, INT_MAX));
auto temp_max = std::vector<std::vector<int>>(n, std::vector<int>(n, INT_MIN));
auto temp_reachable = std::vector<std::vector<bool>>(n, std::vector<bool>(n, false));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
for (int k = 0; k < n; ++k) {
if (result.reachable[i][k] && get(k, j) != 0) {
int new_min = result.min_paths[i][k] + get(k, j);
if (new_min < temp_min[i][j]) {
temp_min[i][j] = new_min;
}
int new_max = result.max_paths[i][k] + get(k, j);
if (new_max > temp_max[i][j]) {
temp_max[i][j] = new_max;
}
temp_reachable[i][j] = true;
}
}
}
}
result.min_paths = temp_min;
result.max_paths = temp_max;
result.reachable = temp_reachable;
}
return result;
}
Graph::PathResult DirectedGraph::findPaths(int from, int to, int maxSteps) const {
PathResult result;
result.exists = false;
result.count = 0;
validateVertex(from);
validateVertex(to);
std::vector<int> currentPath;
findAllPaths(from, to, maxSteps, currentPath, result);
return result;
}
void DirectedGraph::findAllPaths(int current, int target, int stepsLeft,
std::vector<int>& path, PathResult& result) const {
path.push_back(current);
if (current == target && path.size() > 1) {
result.exists = true;
result.count++;
result.paths.push_back(path);
}
if (stepsLeft != 0) {
for (int next = 0; next < getRows(); ++next) {
if (get(current, next) != 0) {
int newStepsLeft = (stepsLeft == -1) ? -1 : stepsLeft - 1;
findAllPaths(next, target, newStepsLeft, path, result);
}
}
}
path.pop_back();
}
Graph::BellmanFordResult DirectedGraph::bellmanFord(int source) const {
int n = getRows();
BellmanFordResult result;
result.iterations = 0;
result.distances.assign(n, INT_MAX);
result.predecessors.assign(n, -1);
result.hasNegativeCycle = false;
result.distances[source] = 0;
std::queue<int> vertexQueue;
std::vector<bool> inQueue(n, false);
std::vector<int> relaxCount(n, 0);
vertexQueue.push(source);
inQueue[source] = true;
relaxCount[source] = 1;
while (!vertexQueue.empty()) {
int u = vertexQueue.front();
vertexQueue.pop();
inQueue[u] = false;
for (int v = 0; v < n; ++v) {
result.iterations++;
int weight = get(u, v);
if (weight != 0 && result.distances[u] != INT_MAX) {
if (result.distances[v] > result.distances[u] + weight) {
result.distances[v] = result.distances[u] + weight;
result.predecessors[v] = u;
relaxCount[v]++;
result.iterations++;
if (relaxCount[v] > n) {
result.hasNegativeCycle = true;
int cycleVertex = v;
for (int i = 0; i < n; ++i) {
cycleVertex = result.predecessors[cycleVertex];
}
std::vector<bool> inCycle(n, false);
for (int v = cycleVertex; ; v = result.predecessors[v]) {
if (inCycle[v]) break;
inCycle[v] = true;
}
for (int v = 0; v < n; ++v) {
if (inCycle[v]) {
result.distances[v] = INT_MIN;
}
}
return result;
}
if (!inQueue[v]) {
vertexQueue.push(v);
inQueue[v] = true;
}
}
}
}
}
return result;
}
std::vector<int> DirectedGraph::getPath(int from, int to,
const std::vector<int>& predecessors,
const std::vector<int>& distances) const {
std::vector<int> path;
if (from == to) {
path.push_back(from);
return path;
}
if (predecessors[to] == -1 || distances[to] == INT_MAX) {
return path;
}
for (int v = to; v != -1; v = predecessors[v]) {
path.push_back(v);
if (path.size() > predecessors.size()) {
return std::vector<int>();
}
}
std::reverse(path.begin(), path.end());
if (path.empty() || path[0] != from) {
return std::vector<int>();
}
return path;
}
void DirectedGraph::generateCapacityAndCostMatrices(std::mt19937& gen) {
int n = getRows();
std::uniform_int_distribution<int> costDist(1, 5);
capacityMatrix.assign(n, std::vector<int>(n, 0));
costMatrix.assign(n, std::vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int weight = get(i, j);
if (weight != 0) {
int capacity = std::max(0, weight);
capacityMatrix[i][j] = capacity;
costMatrix[i][j] = costDist(gen);
} else {
capacityMatrix[i][j] = 0;
costMatrix[i][j] = 0;
}
}
}
}
std::vector<std::vector<int>> DirectedGraph::getCapacityMatrix() const {
return capacityMatrix;
}
std::vector<std::vector<int>> DirectedGraph::getCostMatrix() const {
return costMatrix;
}
bool DirectedGraph::bfsFordFulkerson(int s, int t, const std::vector<std::vector<int>>& residualGraph, std::vector<int>& parent) const {
int n = getRows();
std::fill(parent.begin(), parent.end(), -1);
parent[s] = -2;
std::queue<std::pair<int, int>> q;
q.push({s, INT_MAX});
while (!q.empty()) {
int u = q.front().first;
int current_flow = q.front().second;
q.pop();
for (int v = 0; v < n; ++v) {
if (parent[v] == -1 && residualGraph[u][v] > 0) {
parent[v] = u;
int new_flow = std::min(current_flow, residualGraph[u][v]);
if (v == t) {
return true;
}
q.push({v, new_flow});
}
}
}
return false;
}
DirectedGraph::MaxFlowResult DirectedGraph::maxFlowFordFulkerson(int source, int sink) const {
MaxFlowResult result;
int n = getRows();
try {
validateVertex(source);
validateVertex(sink);
} catch (const std::out_of_range& e) {
result.success = false;
result.message = "Некорректный исток или сток.";
return result;
}
if (source == sink) {
result.success = false;
result.message = "Исток и сток не могут совпадать.";
return result;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (capacityMatrix[i][j] < 0) {
result.success = false;
result.message = "Ошибка: Обнаружена отрицательная пропускная способность.";
return result;
}
}
}
std::vector<std::vector<int>> residualGraph = capacityMatrix;
result.flowMatrix.assign(n, std::vector<int>(n, 0));
std::vector<int> parent(n);
result.maxFlowValue = 0;
result.iterations = 0;
while (bfsFordFulkerson(source, sink, residualGraph, parent)) {
result.iterations++;
int pathFlow = INT_MAX;
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
pathFlow = std::min(pathFlow, residualGraph[u][v]);
}
if (pathFlow == 0) {
break;
}
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
residualGraph[u][v] -= pathFlow;
residualGraph[v][u] += pathFlow;
}
result.maxFlowValue += pathFlow;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (capacityMatrix[i][j] > 0) {
result.flowMatrix[i][j] = capacityMatrix[i][j] - residualGraph[i][j];
if (result.flowMatrix[i][j] < 0) result.flowMatrix[i][j] = 0;
} else {
result.flowMatrix[i][j] = 0;
}
}
}
result.success = true;
result.message = "Максимальный поток успешно найден.";
return result;
}
DirectedGraph::MinCostFlowResult DirectedGraph::minCostFlow(int source, int sink, int targetFlow) const {
MinCostFlowResult result;
int n = getRows();
try {
validateVertex(source);
validateVertex(sink);
} catch (const std::out_of_range& e) {
result.success = false;
result.message = "Некорректный исток или сток.";
return result;
}
if (source == sink) {
result.success = false;
result.message = "Исток и сток не могут совпадать.";
return result;
}
if (targetFlow < 0) {
result.success = false;
result.message = "Целевой поток не может быть отрицательным.";
return result;
}
if (targetFlow == 0) {
result.success = true;
result.targetReached = true;
result.message = "Целевой поток равен 0.";
result.flowMatrix.assign(n, std::vector<int>(n, 0));
return result;
}
if (costMatrix.empty() || costMatrix.size() != n || costMatrix[0].size() != n) {
result.success = false;
result.message = "Матрица стоимостей не инициализирована корректно.";
return result;
}
result.flowMatrix.assign(n, std::vector<int>(n, 0));
result.totalCost = 0;
result.flowAmount = 0;
result.iterations = 0;
while (result.flowAmount < targetFlow) {
result.iterations++;
std::vector<long long> distances(n, LLONG_MAX);
std::vector<int> predecessors(n, -1);
std::vector<int> edge_type(n, 0);
distances[source] = 0;
for (int iter = 1; iter < n; ++iter) {
bool updated = false;
for (int u = 0; u < n; ++u) {
if (distances[u] == LLONG_MAX) continue;
for (int v = 0; v < n; ++v) {
int cap_uv = capacityMatrix[u][v];
int flow_uv = result.flowMatrix[u][v];
if (cap_uv > 0 && flow_uv < cap_uv) {
int cost_uv = costMatrix[u][v];
long long new_dist = distances[u] + cost_uv;
if (new_dist < distances[v]) {
distances[v] = new_dist;
predecessors[v] = u;
edge_type[v] = 1;
updated = true;
}
}
int flow_vu = result.flowMatrix[v][u];
if (capacityMatrix[v][u] > 0 && flow_vu > 0) {
int cost_vu = costMatrix[v][u];
long long new_dist = distances[u] - cost_vu;
if (new_dist < distances[v]) {
distances[v] = new_dist;
predecessors[v] = u;
edge_type[v] = -1;
updated = true;
}
}
}
}
if (!updated) break;
}
if (distances[sink] == LLONG_MAX) {
result.message = "Сток недостижим в остаточной сети. Невозможно достичь целевой поток.";
result.success = false;
break;
}
int deltaFlow = INT_MAX;
int pathCost = 0;
deltaFlow = std::min(deltaFlow, targetFlow - result.flowAmount);
int current_v = sink;
while (current_v != source) {
int prev_u = predecessors[current_v];
if (prev_u == -1) {
result.success = false;
result.message = "Ошибка восстановления пути.";
return result;
}
int type = edge_type[current_v];
int capacity_on_edge;
if (type == 1) {
capacity_on_edge = capacityMatrix[prev_u][current_v] - result.flowMatrix[prev_u][current_v];
} else if (type == -1) {
capacity_on_edge = result.flowMatrix[current_v][prev_u];
} else {
result.success = false;
result.message = "Ошибка типа ребра при восстановлении пути.";
return result;
}
deltaFlow = std::min(deltaFlow, capacity_on_edge);
current_v = prev_u;
}
if (deltaFlow <= 0) {
break;
}
result.flowAmount += deltaFlow;
result.totalCost += (long long)deltaFlow * distances[sink];
result.targetFlowValue = targetFlow;
current_v = sink;
while (current_v != source) {
int prev_u = predecessors[current_v];
int type = edge_type[current_v];
if (type == 1) {
result.flowMatrix[prev_u][current_v] += deltaFlow;
} else if (type == -1) {
result.flowMatrix[current_v][prev_u] -= deltaFlow;
}
current_v = prev_u;
}
}
if (result.flowAmount >= targetFlow) {
result.targetReached = true;
result.message = "Целевой поток достигнут.";
} else if (result.success) {
result.message = "Достигнут максимально возможный поток ("
+ std::to_string(result.flowAmount)
+ "), который меньше целевого ("
+ std::to_string(targetFlow) + ").";
result.success = false;
}
return result;
}