-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxFlowControl.cs
More file actions
455 lines (387 loc) · 17.3 KB
/
MaxFlowControl.cs
File metadata and controls
455 lines (387 loc) · 17.3 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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1
{
public class MaxFlowControl : BaseGraphControl
{
private Button btnGenerate;
private Button btnRun;
private Button btnReset;
private Button btnSave;
private Button btnLoad;
private Button btnAddNode;
private Button btnAddEdge;
private Button btnMoveNode;
private Button btnSetSource;
private Button btnSetSink;
private Button btnCancelMode;
private NumericUpDown numNodes;
private Label lblResult;
private Label lblMode;
private WeightedGraph.Node sourceNode = null;
private WeightedGraph.Node sinkNode = null;
private EditMode currentMode = EditMode.None;
private enum EditMode { None, AddNode, AddEdge, MoveNode, SetSource, SetSink }
public MaxFlowControl() : base()
{
graph = new WeightedGraph(true);
InitializeControls();
}
private void InitializeControls()
{
var flowPanel = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.TopDown,
WrapContents = false,
AutoScroll = true,
Padding = new Padding(5)
};
var titleLabel = CreateLabel("Алгоритм Эдмондса-Карпа", true, 11);
titleLabel.ForeColor = Color.DarkBlue;
flowPanel.Controls.Add(titleLabel);
flowPanel.Controls.Add(new Label { Height = 5 });
var genPanel = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
genPanel.Controls.Add(CreateLabel("Узлы:"));
numNodes = new NumericUpDown { Width = 55, Minimum = 4, Maximum = 12, Value = 6 };
genPanel.Controls.Add(numNodes);
btnGenerate = CreateButton("🎲 Генерировать", Color.LightBlue, (s, e) => GenerateGraph());
genPanel.Controls.Add(btnGenerate);
flowPanel.Controls.Add(genPanel);
flowPanel.Controls.Add(new Label { Height = 10 });
flowPanel.Controls.Add(CreateLabel("Редактирование:", true, 10));
var editPanel1 = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
btnAddNode = CreateButton("+ Узел", Color.LightGreen, (s, e) => SetMode(EditMode.AddNode));
btnAddNode.Width = 80;
btnAddEdge = CreateButton("+ Ребро", Color.LightYellow, (s, e) => SetMode(EditMode.AddEdge));
btnAddEdge.Width = 80;
btnMoveNode = CreateButton("✋ Двигать", Color.LightSkyBlue, (s, e) => SetMode(EditMode.MoveNode));
btnMoveNode.Width = 80;
editPanel1.Controls.AddRange(new Control[] { btnAddNode, btnAddEdge, btnMoveNode });
flowPanel.Controls.Add(editPanel1);
var editPanel2 = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
btnSetSource = CreateButton("Исток (S)", Color.Lime, (s, e) => SetMode(EditMode.SetSource));
btnSetSource.Width = 95;
btnSetSink = CreateButton("Сток (T)", Color.Coral, (s, e) => SetMode(EditMode.SetSink));
btnSetSink.Width = 95;
editPanel2.Controls.AddRange(new Control[] { btnSetSource, btnSetSink });
flowPanel.Controls.Add(editPanel2);
lblMode = new Label
{
Text = "Режим: просмотр",
AutoSize = true,
ForeColor = Color.DarkBlue,
Font = new Font("Segoe UI", 9, FontStyle.Italic),
MaximumSize = new Size(250, 0)
};
flowPanel.Controls.Add(lblMode);
btnCancelMode = CreateButton("↩ Отмена режима", Color.Gainsboro, (s, e) => SetMode(EditMode.None));
flowPanel.Controls.Add(btnCancelMode);
flowPanel.Controls.Add(new Label { Height = 10 });
var lblSpeed = CreateLabel("Скорость анимации: 500мс");
flowPanel.Controls.Add(lblSpeed);
flowPanel.Controls.Add(CreateSpeedTrackBar(lblSpeed));
flowPanel.Controls.Add(new Label { Height = 10 });
btnRun = CreateButton("▶ Найти макс. поток", Color.RoyalBlue, async (s, e) => await RunMaxFlow());
btnRun.ForeColor = Color.White;
btnRun.Width = 180;
btnRun.Height = 38;
btnRun.Font = new Font("Segoe UI", 10, FontStyle.Bold);
flowPanel.Controls.Add(btnRun);
lblResult = new Label
{
Text = "Максимальный поток: —",
AutoSize = true,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.DarkGreen
};
flowPanel.Controls.Add(lblResult);
flowPanel.Controls.Add(new Label { Height = 10 });
btnReset = CreateButton("🔄 Сбросить", Color.Silver, (s, e) => ResetGraph());
flowPanel.Controls.Add(btnReset);
flowPanel.Controls.Add(new Label { Height = 15 });
flowPanel.Controls.Add(CreateLabel("Файлы:", true, 10));
var filePanel = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
btnSave = CreateButton("💾 Сохранить", Color.LightSteelBlue, (s, e) => SaveGraph());
btnSave.Width = 115;
btnLoad = CreateButton("📂 Загрузить", Color.LightSteelBlue, (s, e) => LoadGraph());
btnLoad.Width = 115;
filePanel.Controls.AddRange(new Control[] { btnSave, btnLoad });
flowPanel.Controls.Add(filePanel);
controlPanel.Controls.Add(flowPanel);
}
private void SetMode(EditMode mode)
{
currentMode = mode;
selectedNode = null;
isDragging = false;
draggingNode = null;
lblMode.Text = mode switch
{
EditMode.AddNode => "Режим: добавление узла",
EditMode.AddEdge => "Режим: добавление ребра",
EditMode.MoveNode => "Режим: перемещение узлов",
EditMode.SetSource => "Режим: установка истока",
EditMode.SetSink => "Режим: установка стока",
_ => "Режим: просмотр"
};
lblMode.ForeColor = mode == EditMode.None ? Color.DarkBlue : Color.DarkRed;
drawPanel.Cursor = mode == EditMode.MoveNode ? Cursors.SizeAll : Cursors.Default;
RefreshGraph();
}
private void GenerateGraph()
{
graph = new WeightedGraph(true);
int n = (int)numNodes.Value;
graph.GenerateRandom(n, n * 2, drawPanel.Width, drawPanel.Height, 5, 20);
if (graph.Nodes.Count >= 2)
{
sourceNode = graph.Nodes[0];
sinkNode = graph.Nodes[graph.Nodes.Count - 1];
}
Log($"Сгенерирована сеть: {graph.Nodes.Count} узлов, {graph.Edges.Count} рёбер");
UpdateMatrix();
RefreshGraph();
}
private void ResetGraph()
{
graph.ResetFlow();
graph.ResetState();
lblResult.Text = "Максимальный поток: —";
SetMode(EditMode.None);
RefreshGraph();
}
protected override void OnGraphLoaded()
{
if (graph.Nodes.Count >= 2)
{
sourceNode = graph.Nodes[0];
sinkNode = graph.Nodes[graph.Nodes.Count - 1];
}
}
protected override void DrawPanel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.White);
GraphRenderer.DrawGraph(e.Graphics, graph, selectedNode, sourceNode, sinkNode,
showWeights: true, showFlow: true);
var legend = new Dictionary<Color, string>
{
{ Color.Lime, "Исток (S)" },
{ Color.Coral, "Сток (T)" },
{ Color.Yellow, "В пути BFS" },
{ Color.Green, "Использовано" }
};
GraphRenderer.DrawLegend(e.Graphics, legend);
}
protected override void OnMouseDownHandler(MouseEventArgs e)
{
var clickedNode = FindNodeAtPosition(e.Location);
switch (currentMode)
{
case EditMode.AddNode:
if (clickedNode == null)
{
graph.AddNode(e.Location);
Log($"Добавлен узел {graph.Nodes.Count - 1}");
UpdateMatrix();
RefreshGraph();
}
break;
case EditMode.AddEdge:
if (clickedNode != null)
{
if (selectedNode == null)
{
selectedNode = clickedNode;
lblMode.Text = $"Выбран узел {clickedNode.Id}\nКликните на второй";
}
else if (clickedNode != selectedNode)
{
string input = ShowInputDialog("Пропускная способность:", "Capacity", "10");
if (!string.IsNullOrEmpty(input) && int.TryParse(input, out int cap) && cap > 0)
{
graph.AddEdge(selectedNode, clickedNode, cap);
Log($"Добавлено ребро {selectedNode.Id} → {clickedNode.Id} (capacity: {cap})");
UpdateMatrix();
}
selectedNode = null;
lblMode.Text = "Режим: добавление ребра";
RefreshGraph();
}
}
break;
case EditMode.MoveNode:
if (clickedNode != null)
{
StartDragging(clickedNode, e.Location);
}
break;
case EditMode.SetSource:
if (clickedNode != null && clickedNode != sinkNode)
{
sourceNode = clickedNode;
Log($"Исток: узел {clickedNode.Id}");
SetMode(EditMode.None);
RefreshGraph();
}
break;
case EditMode.SetSink:
if (clickedNode != null && clickedNode != sourceNode)
{
sinkNode = clickedNode;
Log($"Сток: узел {clickedNode.Id}");
SetMode(EditMode.None);
RefreshGraph();
}
break;
default:
selectedNode = clickedNode;
RefreshGraph();
break;
}
}
protected override void DrawPanel_MouseMove(object sender, MouseEventArgs e)
{
if (isRunning) return;
if (currentMode == EditMode.MoveNode && isDragging && draggingNode != null)
{
int newX = e.X - dragOffset.X;
int newY = e.Y - dragOffset.Y;
int margin = 30;
newX = Math.Max(margin, Math.Min(drawPanel.Width - margin, newX));
newY = Math.Max(margin, Math.Min(drawPanel.Height - margin, newY));
draggingNode.Position = new Point(newX, newY);
RefreshGraph();
}
else if (currentMode == EditMode.MoveNode)
{
var node = FindNodeAtPosition(e.Location);
drawPanel.Cursor = node != null ? Cursors.SizeAll : Cursors.Hand;
}
}
protected override void DrawPanel_MouseUp(object sender, MouseEventArgs e)
{
if (currentMode == EditMode.MoveNode && isDragging && draggingNode != null)
{
Log($"Узел {draggingNode.Id} перемещён");
isDragging = false;
draggingNode = null;
RefreshGraph();
}
}
private async Task RunMaxFlow()
{
if (graph.Nodes.Count < 2 || sourceNode == null || sinkNode == null)
{
MessageBox.Show("Установите исток и сток!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
isRunning = true;
SetButtonsEnabled(false);
graph.ResetFlow();
graph.ResetState();
Log("\n=== Алгоритм Эдмондса-Карпа ===");
int maxFlow = await EdmondsKarp();
lblResult.Text = $"Максимальный поток: {maxFlow}";
Log($"=== Максимальный поток = {maxFlow} ===\n");
isRunning = false;
SetButtonsEnabled(true);
}
private async Task<int> EdmondsKarp()
{
int n = graph.Nodes.Count;
int[,] residual = new int[n, n];
foreach (var edge in graph.Edges)
residual[edge.From.Id, edge.To.Id] = edge.Capacity;
int[] parent = new int[n];
int maxFlow = 0;
int step = 1;
while (BFS(residual, sourceNode.Id, sinkNode.Id, parent))
{
List<int> path = new List<int>();
for (int v = sinkNode.Id; v != sourceNode.Id; v = parent[v])
path.Add(v);
path.Add(sourceNode.Id);
path.Reverse();
Log($"Шаг {step}: Путь: {string.Join(" → ", path)}");
foreach (var edge in graph.Edges)
edge.IsHighlighted = false;
for (int i = 0; i < path.Count - 1; i++)
{
var edge = graph.Edges.Find(ed => ed.From.Id == path[i] && ed.To.Id == path[i + 1]);
if (edge != null) edge.IsHighlighted = true;
graph.Nodes[path[i]].Color = Color.Yellow;
}
graph.Nodes[path[path.Count - 1]].Color = Color.Yellow;
RefreshGraph();
await Task.Delay(animationDelay);
int pathFlow = int.MaxValue;
for (int v = sinkNode.Id; v != sourceNode.Id; v = parent[v])
pathFlow = Math.Min(pathFlow, residual[parent[v], v]);
Log($"Поток: {pathFlow}");
for (int v = sinkNode.Id; v != sourceNode.Id; v = parent[v])
{
int u = parent[v];
residual[u, v] -= pathFlow;
residual[v, u] += pathFlow;
var edge = graph.Edges.Find(ed => ed.From.Id == u && ed.To.Id == v);
if (edge != null)
{
edge.Flow += pathFlow;
edge.IsInResult = true;
}
}
maxFlow += pathFlow;
Log($"Общий поток: {maxFlow}");
foreach (var node in graph.Nodes)
node.Color = Color.LightBlue;
foreach (var edge in graph.Edges)
edge.IsHighlighted = false;
RefreshGraph();
await Task.Delay(animationDelay / 2);
step++;
}
Log("Путей больше нет.");
return maxFlow;
}
private bool BFS(int[,] residual, int s, int t, int[] parent)
{
int n = graph.Nodes.Count;
bool[] visited = new bool[n];
Queue<int> queue = new Queue<int>();
queue.Enqueue(s);
visited[s] = true;
parent[s] = -1;
while (queue.Count > 0)
{
int u = queue.Dequeue();
for (int v = 0; v < n; v++)
{
if (!visited[v] && residual[u, v] > 0)
{
queue.Enqueue(v);
parent[v] = u;
visited[v] = true;
if (v == t) return true;
}
}
}
return false;
}
private void SetButtonsEnabled(bool enabled)
{
btnRun.Enabled = enabled;
btnGenerate.Enabled = enabled;
btnAddNode.Enabled = enabled;
btnAddEdge.Enabled = enabled;
btnMoveNode.Enabled = enabled;
btnSetSource.Enabled = enabled;
btnSetSink.Enabled = enabled;
btnSave.Enabled = enabled;
btnLoad.Enabled = enabled;
}
}
}