forked from ngthanhtrung23/CompetitiveProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA.cpp
More file actions
104 lines (90 loc) · 1.85 KB
/
A.cpp
File metadata and controls
104 lines (90 loc) · 1.85 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
#include <bits/stdc++.h>
using namespace std;
const int oo = 27081993;
struct Edge
{
int x, y, cap, flow, cost;
};
int n, dist[33], tr[33];
vector <int> a[33];
vector <Edge> edges;
void addEdge(int x, int y, int cap, int cost)
{
a[x].push_back(edges.size());
edges.push_back({x, y, cap, 0, cost});
a[y].push_back(edges.size());
edges.push_back({y, x, 0, 0, -cost});
}
int negativeCycle()
{
int lastUpdated = 0;
memset(dist, 0, sizeof dist);
memset(tr, -1, sizeof tr);
for (int turn = 0; turn < n + 3; turn++)
{
int found = 0;
for (int i = 0; i < edges.size(); i++)
{
Edge e = edges[i];
if (e.flow < e.cap && dist[e.y] > dist[e.x] + e.cost)
{
found = 1;
lastUpdated = e.y;
dist[e.y] = dist[e.x] + e.cost;
tr[e.y] = i;
}
}
if (!found)
return 0;
}
return lastUpdated;
}
int modify(int x)
{
int minCap = oo;
vector <int> edgeList, flag(edges.size(), 0);
while (1)
{
int i = tr[x];
if (i < 0) break;
Edge e = edges[i];
if (flag[i])
{
while (edgeList[0] != i)
edgeList.erase(edgeList.begin());
break;
}
minCap = min(minCap, e.cap - e.flow);
edgeList.push_back(i);
flag[i] = 1;
x = e.x;
}
int res = 0;
for (auto i : edgeList)
{
edges[i].flow += minCap;
res += minCap * edges[i].cost;
edges[i ^ 1].flow -= minCap;
}
return res;
}
int main()
{
freopen("arbitrage.in", "r", stdin);
freopen("arbitrage.out", "w", stdout);
int m, x, y, cost, cap;
cin >> n >> m;
while (m--)
{
cin >> x >> y >> cost >> cap;
addEdge(x, y, cap, -cost);
}
int ans = 0;
while (1)
{
int x = negativeCycle();
if (!x) break;
ans += modify(x);
}
cout << -ans << endl;
}